package org.darkforest.admin.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.util.CellRangeAddress;
import org.darkforest.annotation.ArchivesLog;
import org.darkforest.common.services.*;
import org.darkforest.common.util.CalculateUserAgeUtils;
import org.darkforest.common.util.DateUtil;
import org.darkforest.common.util.ExcelUtil;
import org.darkforest.common.util.Utils;
import org.darkforest.dao.mapper.*;
import org.darkforest.model.*;
import org.darkforest.ucenter.auth.AuthPassport;
import org.darkforest.vo.AjaxReturnData;
import org.darkforest.vo.AjaxReturnEntity;
import org.darkforest.vo.MemberBase;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("operation")
public class HealthController {

    org.slf4j.Logger logger = LoggerFactory.getLogger(HealthController.class);

    @Autowired
    private HealthOrgMapper healthOrgMapper;
    @Autowired
    private HealthOrgAppointmentMapper healthOrgAppointmentMapper;
    @Autowired
    private HealthCycleMapper healthCycleMapper;
    @Autowired
    private HealthPackageMapper healthPackageMapper;
    @Autowired
    private HealthDeptMapper healthDeptMapper;
    @Autowired
    private HealthUserMapper healthUserMapper;
    @Autowired
    private HealthUserAppointmentMapper healthUserAppointmentMapper;

    @Autowired
    private HealthOrgAppointmentService appointmentService;
    @Autowired
    private HealthCycleService healthCycleService;
    @Autowired
    private HealthPackageService healthPackageService;
    @Autowired
    private HealthDeptmentService healthDeptmentService;
    @Autowired
    private HealthUserService healthUserService;

    @Autowired
    private MemberMsgTplMapper memberMsgTplMapper;
    @Autowired
    private MessageAndNoticeService messageAndNoticeService;


    /*****************************************体检机构管理*****************************************************************************/
    /**
     *  体检机构一览
     *
     * @param request
     * @return
     */
    @RequestMapping("health")
    public ModelAndView healthList(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("operation/health/orgList");

        // 登录者自己部门的检索条件
        MemberBase memberBase = (MemberBase)request.getSession().getAttribute("memInfo");
        if (memberBase != null && memberBase.getHealthDeptId() != null ) {
            view = new ModelAndView("operation/health/userList");
            // 检索条件
            Integer deptId = memberBase.getHealthDeptId();
            //用户信息查询
            HealthUser healthUserSearch = new HealthUser();
            // 改页处理用
            String start = request.getParameter("start");
            if (StringUtils.isNotEmpty(start)) {
                healthUserSearch.setStart(Integer.valueOf(start));
            }
            healthUserSearch.setDeptId(deptId);
            //查询结果
            List<HealthUser> healthUserList = healthUserMapper.selectListByCondition(healthUserSearch);
            for (int i = 0; healthUserList != null && i < healthUserList.size(); i++) {
                //用户预约信息查询
                HealthUserAppointment huaSearch = new HealthUserAppointment();
                huaSearch.setUserId(healthUserList.get(i).getUserId());
                huaSearch.setPageSwitch(false);
                //查询结果
                List<HealthUserAppointment> huaList = healthUserAppointmentMapper.selectListByCondition(huaSearch);
                if (huaList != null && huaList.size() > 0) {
                    healthUserList.get(i).setHuaList(huaList);
                }
            }
            healthUserSearch.setResultList(healthUserList);

            // 可选择体检机构的取得
            HealthOrg healthOrg = new HealthOrg();
            healthOrg.setPageSwitch(false);
            List<HealthOrg> healthOrgList = healthOrgMapper.selectListByCondition(healthOrg);
            view.addObject("orgList", healthOrgList);
            // 可选择业务单元的取得
            HealthDept healthDept = new HealthDept();
            healthDept.setPageSwitch(false);
            List<HealthDept> healthDeptList = healthDeptMapper.selectListByCondition(healthDept);
            view.addObject("deptList", healthDeptList);
            //查询结果
            view.addObject("page", healthUserSearch);
            view.addObject("memberBase", memberBase);
            //查询条件
            view.addObject("deptId", deptId);
            return view;
        }

        // 检索条件
        String orgName = request.getParameter("orgName");
        // 改页处理用
        String start = request.getParameter("start");

        HealthOrg healthOrg = new HealthOrg();
        healthOrg.setOrgName(orgName);
        // 改页处理时
        if (start != null && !"".equals(start)) {
            healthOrg.setStart(Integer.valueOf(start));
        }

        List<HealthOrg> orgList = healthOrgMapper.selectListByCondition(healthOrg);

        // 套餐信息的设定
        for (HealthOrg orgInfo: orgList) {
            // 根据pkgId取得套餐信息
            List<HealthPackage> pkgList = new ArrayList<HealthPackage>();
            String pkgIds = orgInfo.getPkgIds();
            if (!StringUtils.isBlank(pkgIds)) {
                String[] pkgIdArray = pkgIds.split(",");
                for (String pkgId: pkgIdArray) {
                    HealthPackage healthPackage = healthPackageMapper.selectByPrimaryKey(Integer.valueOf(pkgId));
                    if (healthPackage != null &&  "1".equals(healthPackage.getPkgState())) {
                        pkgList.add(healthPackage);
                    }
                }
            }
            orgInfo.setPkgList(pkgList);
        }

        healthOrg.setResultList(orgList);
        view.addObject("page", healthOrg);

        return view;
    }

    /**
     *  体检机构添加
     *
     * @return
     */
    @RequestMapping("health/toAddOrg")
    public ModelAndView orgAdd() {
        ModelAndView modelAndView = new ModelAndView("operation/health/orgAdd");

        // 体检套餐的选择
        HealthPackage healthPackage = new HealthPackage();
        healthPackage.setPageSwitch(false);
        healthPackage.setPkgState("1");
        List<HealthPackage> healthPackageList = healthPackageMapper.selectListByCondition(healthPackage);
        modelAndView.addObject("pgkList", healthPackageList);

        return modelAndView;
    }
    @RequestMapping(value = "health/orgDoAdd")
    public ModelAndView doAddOrg(HealthOrg healthOrg) {
        ModelAndView modelAndView = new ModelAndView("msg");
        int i = healthOrgMapper.insert(healthOrg);
        if (i > 0) {
            modelAndView.addObject("msg", "体检机构新增成功");
        } else {
            modelAndView.addObject("msg", "体检机构新增失败");
        }
        modelAndView.addObject("returnUrl", "operation/health");
        return modelAndView;
    }

    /**
     *  体检机构重名CHECK
     *
     * @param healthOrg
     * @return
     */
    @RequestMapping("health/checkOrgName")
    @ResponseBody
    public Boolean checkOrgName(HealthOrg healthOrg) {
        healthOrg.setPageSwitch(false);
        List<HealthOrg> orgList = healthOrgMapper.selectListByCondition(healthOrg);
        if (orgList.size() == 0) {
            return true;
        }

        // 添加时
        if (healthOrg.getOrgId() == null) {
            // 件数大于0时， 标识数据库内有重复数据  return false;
        } else {
            // 修改时
            if (orgList.size() == 1) {
                // 修改的当前记录的数据时
                if (orgList.get(0).getOrgId().intValue() == healthOrg.getOrgId().intValue()) {
                    return true;
                }
            } else {
                // 件数大于1时， 标识数据库内有重复数据  return false;
            }
        }

        // 添加时 或  修改的其他记录的数据时
        return false;
    }

    /**
     *  体检机构修改
     *
     * @param orgId
     * @return
     */
    @RequestMapping(value = "health/toModifyOrg")
    public ModelAndView toEditOrg(String orgId) {
        ModelAndView view = new ModelAndView("operation/health/orgEdit");
        HealthOrg healthOrg = healthOrgMapper.selectByPrimaryKey(Integer.valueOf(orgId));
        view.addObject("org", healthOrg);

        // 体检套餐的选择
        HealthPackage healthPackage = new HealthPackage();
        healthPackage.setPageSwitch(false);
        healthPackage.setPkgState("1");
        List<HealthPackage> healthPackageList = healthPackageMapper.selectListByCondition(healthPackage);
        view.addObject("pgkList", healthPackageList);

        return view;
    }
    @RequestMapping(value = "health/orgDoEdit")
    public ModelAndView doEditOrg(HealthOrg healthOrg) {
        ModelAndView modelAndView = new ModelAndView("msg");
        // 全项目更新
        int i = healthOrgMapper.updateByPrimaryKey(healthOrg);
        if (i > 0) {
            modelAndView.addObject("msg", "体检机构修改成功");
        } else {
            modelAndView.addObject("msg", "体检机构修改失败");
        }
        modelAndView.addObject("returnUrl", "operation/health");
        return modelAndView;
    }

    /**
     *  体检机构删除
     *
     * @param request
     * @return
     */
    @RequestMapping("health/delOrg")
    public ModelAndView delOrg(HttpServletRequest request) {
        String[] orgId = request.getParameterValues("orgId");
        int i = 0;
        for (String id : orgId) {
            i += healthOrgMapper.deleteByPrimaryKey(Integer.parseInt(id));
        }
        ModelAndView modelAndView = new ModelAndView("msg");
        if (i == orgId.length) {
            modelAndView.addObject("msg", "体检机构删除成功");
        } else {
            modelAndView.addObject("msg", "体检机构删除失败");
        }
        modelAndView.addObject("returnUrl", "operation/health");
        return modelAndView;
    }

    /**
     *  体检机构预约信息页面显示
     *
     * @param orgId
     * @return
     */
    @RequestMapping(value = "health/appointment")
    public ModelAndView toAppointment(String orgId) {
        ModelAndView view = new ModelAndView("operation/health/appointment");
        HealthOrg healthOrg = healthOrgMapper.selectByPrimaryKey(Integer.valueOf(orgId));
        view.addObject("org", healthOrg);

        // 当前年月的取得：yyyy-MM
        String strYearMonth = Utils.getCurMonth();
        view.addObject("oaYear", strYearMonth.split("-")[0]);
        view.addObject("oaMonth", strYearMonth.split("-")[1]);

        return view;
    }

    /**
     *  体检机构预约信息检索
     *
     * @param orgId
     * @return
     */
    @RequestMapping(value = "health/searchAppointment")
    @ResponseBody
    public List<HealthOrgAppointment> searchAppointment(String orgId, String oaYear, String oaMonth) {
        HealthOrgAppointment appointment = new HealthOrgAppointment();
        appointment.setOrgId(Integer.valueOf(orgId));
        // 年月结合条件
        if (StringUtils.isNotEmpty(oaYear) && StringUtils.isNotEmpty(oaMonth)) {
            appointment.setYearMonth(oaYear+"-"+oaMonth);
        }

        List<HealthOrgAppointment> appointmentList = healthOrgAppointmentMapper.selectListByCondition(appointment);

        return appointmentList;
    }

    /**
     *  体检机构预约信息管理
     *
     * @param healthOrg
     * @return
     */
    @RequestMapping(value = "health/batchAppointment")
    @ResponseBody
    public boolean doAddAppointmentBatch(HealthOrg healthOrg){

        int count = 0;
        List<HealthOrgAppointment> appointmentList = healthOrg.getAppointmentList();

        // 共通项目的设定
        for (HealthOrgAppointment appointment: appointmentList) {
            appointment.setOrgId(healthOrg.getOrgId());
            appointment.setAppointmentDate(DateUtil.toUnixTimeStampByDate(appointment.getAppointmentDateStr()));
            appointment.setCancelTime(DateUtil.toUnixTimeStamp(appointment.getCancelTimeStr()));
        }

        // 判断选择的机构、选择的年月的预约信息是登录还是更新
        if ("add".equals(healthOrg.getAddOrUpdate())) {
            count = healthOrgAppointmentMapper.batchAddAppointment(appointmentList);
        } else {
            count = appointmentService.batchUpdateAppointment(appointmentList);
        }

        if (appointmentList.size() == count) {
            return true;
        }

        return false;
    }


    /*****************************************体检周期管理*****************************************************************************/
    /**
     * 体检周期列表
     *
     * @param request
     * @return
     */
    @RequestMapping("health/cycleList")
    public ModelAndView healthCycleList(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("operation/health/cycleList");

        // 检索条件
        String cycleName = request.getParameter("cycleName");
        // 改页处理用
        String start = request.getParameter("start");

        HealthCycle healthCycle = new HealthCycle();
        if (StringUtils.isNotEmpty(cycleName)) {
            healthCycle.setCycleName(cycleName);
        }

        // 改页处理时
        if (StringUtils.isNotEmpty(start)) {
            healthCycle.setStart(Integer.valueOf(start));
        }

        List<HealthCycle> healthCycleList = healthCycleMapper.selectListByCondition(healthCycle);
        healthCycle.setResultList(healthCycleList);

        modelAndView.addObject("page", healthCycle);

        return modelAndView;
    }

    /**
     * 体检周期增加
     *
     * @return
     */
    @RequestMapping(value = "health/toAddCycle")
    public ModelAndView toAddHealthCycle() {
        ModelAndView mv = new ModelAndView("operation/health/cycleAdd");

        return mv;
    }

    @RequestMapping(value = "health/doAddCycle")
    @ArchivesLog(operationDescription = "新增体检周期")
    public ModelAndView doAddCycle(HealthCycle healthCycle) {
        ModelAndView mv = new ModelAndView("msg");

        // 体检年度、预约开始日期、预约结束日期关联CHECK
        boolean errFlg = false;
        // 体检年度的数据的取得
        HealthCycle selectCycle = new HealthCycle();
        selectCycle.setPageSwitch(false);
        selectCycle.setCycleYear(healthCycle.getCycleYear());
        List<HealthCycle> cycleList = healthCycleMapper.selectListByCondition(selectCycle);
        if (cycleList != null && cycleList.size() > 0) {
            for (HealthCycle dbHealthCycle :cycleList) {
                // 起止时间段有重复
                // 数据库： 2018-7-20 <----> 2018-8-20;
                //   页面：开始时间在以上时间之间（包含开始时间和结束时间都在以上时间之间）
                if (dbHealthCycle.getStartDate() < healthCycle.getStartDate() &&
                        dbHealthCycle.getEndDate() > healthCycle.getStartDate()) {
                    errFlg = true;
                    break;
                }
                // 数据库： 2018-7-20 <----> 2018-8-20;
                //   页面：开始时间在以上结束之间（包含开始时间和结束时间都在以上时间之间）
                if (dbHealthCycle.getStartDate() < healthCycle.getEndDate() &&
                        dbHealthCycle.getEndDate() > healthCycle.getEndDate()) {
                    errFlg = true;
                    break;
                }
                // 数据库： 2018-7-20 <----> 2018-8-20;
                //   页面：2018-6-21 <----> 2018-8-21
                if (dbHealthCycle.getStartDate() > healthCycle.getStartDate() &&
                        dbHealthCycle.getEndDate() < healthCycle.getEndDate()) {
                    errFlg = true;
                    break;
                }
            }
        }

        if (errFlg) {
            mv.addObject("msg", "体检年度内预约开始日期和结束日期的周期已存在,请重新设定");
            // 返回到添加页面 mv.addObject("returnUrl", "operation/health/cycleList");
            return mv;
        }

        // 体检周期状态CHECK
        // 关闭状态的数据不CKECK
        // 如果状态是开启时，进行以下判断处理
        if ("1".equals(healthCycle.getCycleState())) {
            // 按状态检索
            HealthCycle selectStateCycle = new HealthCycle();
            selectStateCycle.setPageSwitch(false);
            selectStateCycle.setCycleState(healthCycle.getCycleState());
            List<HealthCycle> cycleStateList = healthCycleMapper.selectListByCondition(selectStateCycle);
            // 有状态相同的时
            if (cycleStateList != null && cycleStateList.size() > 0) {
                // 添加时
                if (healthCycle.getCycleId() == null) {
                    errFlg = true;
                }
            }

            if (errFlg) {
                mv.addObject("msg", "最多只能有一个预约周期是开启状态,请重新设定");
                //返回到添加页面  mv.addObject("returnUrl", "operation/health/cycleList");
                return mv;
            }
        }

        int i = healthCycleMapper.insert(healthCycle);
        if (i > 0) {
            mv.addObject("msg", "体检周期新增成功");
        } else {
            mv.addObject("msg", "体检周期新增失败");
        }
        mv.addObject("returnUrl", "operation/health/cycleList");
        return mv;
    }

    /**
     * 体检周期修改
     *
     * @param cycleId
     * @return
     */
    @RequestMapping(value = "health/toEditCycle")
    public ModelAndView toModifyCycle(Integer cycleId) {
        ModelAndView mv = new ModelAndView("operation/health/cycleEdit");

        HealthCycle healthCycle = healthCycleMapper.selectByPrimaryKey(cycleId);
        mv.addObject("healthCycle", healthCycle);

        return mv;
    }

    @RequestMapping(value = "health/doEditCycle")
    @ArchivesLog(operationDescription = "修改体检周期")
    public ModelAndView doModifyHealthCycle(HealthCycle healthCycle) {
        ModelAndView mv = new ModelAndView("msg");

        // 体检年度、预约开始日期、预约结束日期关联CHECK
        boolean errFlg = false;
        // 体检年度的数据的取得
        HealthCycle selectCycle = new HealthCycle();
        selectCycle.setPageSwitch(false);
        selectCycle.setCycleYear(healthCycle.getCycleYear());
        List<HealthCycle> cycleList = healthCycleMapper.selectListByCondition(selectCycle);
        if (cycleList != null && cycleList.size() > 0) {
            for (HealthCycle dbHealthCycle :cycleList) {
                // 起止时间段有重复
                // 数据库： 2018-7-20 <----> 2018-8-20;
                //   页面：开始时间在以上时间之间（包含开始时间和结束时间都在以上时间之间）
                if (dbHealthCycle.getStartDate() < healthCycle.getStartDate() &&
                        dbHealthCycle.getEndDate() > healthCycle.getStartDate()) {

                    // CHECH数据不是当前修改的记录
                    if (dbHealthCycle.getCycleId().intValue() != healthCycle.getCycleId().intValue()) {
                        errFlg = true;
                        break;
                    }
                }
                // 数据库： 2018-7-20 <----> 2018-8-20;
                //   页面：开始时间在以上结束之间（包含开始时间和结束时间都在以上时间之间）
                if (dbHealthCycle.getStartDate() < healthCycle.getEndDate() &&
                        dbHealthCycle.getEndDate() > healthCycle.getEndDate()) {

                    // CHECH数据不是当前修改的记录
                    if (dbHealthCycle.getCycleId().intValue() != healthCycle.getCycleId().intValue()) {
                        errFlg = true;
                        break;
                    }
                }
                // 数据库： 2018-7-20 <----> 2018-8-20;
                //   页面：2018-6-21 <----> 2018-8-21
                if (dbHealthCycle.getStartDate() > healthCycle.getStartDate() &&
                        dbHealthCycle.getEndDate() < healthCycle.getEndDate()) {

                    // CHECH数据不是当前修改的记录
                    if (dbHealthCycle.getCycleId().intValue() != healthCycle.getCycleId().intValue()) {
                        errFlg = true;
                        break;
                    }
                }
            }
        }

        if (errFlg) {
            mv.addObject("msg", "体检年度内预约开始日期和结束日期的周期已存在,请重新设定");
            //返回到修改页面 mv.addObject("returnUrl", "operation/health/cycleList");
            return mv;
        }

        // 体检周期状态CHECK
        // 关闭状态的数据不CKECK
        // 如果状态是开启时，进行以下判断处理
        if ("1".equals(healthCycle.getCycleState())) {
            // 按状态检索
            HealthCycle selectStateCycle = new HealthCycle();
            selectStateCycle.setPageSwitch(false);
            selectStateCycle.setCycleState(healthCycle.getCycleState());
            List<HealthCycle> cycleStateList = healthCycleMapper.selectListByCondition(selectStateCycle);
            // 有状态相同的时
            if (cycleStateList != null && cycleStateList.size() > 0) {
                // 修改时
                for (HealthCycle dbHealthCycle :cycleStateList) {
                    // CHECH数据不是当前修改的记录
                    if (dbHealthCycle.getCycleId().intValue() != healthCycle.getCycleId().intValue()) {
                        errFlg = true;
                    }
                }
            }

            if (errFlg) {
                mv.addObject("msg", "最多只能有一个预约周期是开启状态,请重新设定");
                //返回到修改页面  mv.addObject("returnUrl", "operation/health/cycleList");
                return mv;
            }
        }

        int i = healthCycleMapper.updateByPrimaryKeySelective(healthCycle);
        if (i > 0) {
            mv.addObject("msg", "体检周期修改成功");
        } else {
            mv.addObject("msg", "体检周期修改失败");
        }
        mv.addObject("returnUrl", "operation/health/cycleList");

        return mv;
    }

    /**
     * 体检周期删除
     *
     * @param request
     * @return
     */
    @RequestMapping("health/deleteCycle")
    @ArchivesLog(operationDescription = "删除体检周期")
    public ModelAndView deleteHealthCycle(HttpServletRequest request) {
        String[] id = request.getParameterValues("cycleId");

        ModelAndView mv = new ModelAndView("msg");

        int i = healthCycleService.deleteHealthCycle(id);
        if (i ==  1) {
            mv.addObject("msg", "体检周期删除成功");
        } else {
            mv.addObject("msg", "体检周期删除失败");
        }
        mv.addObject("returnUrl", "operation/health/cycleList");

        return mv;
    }

    /**
     *  体检周期名称重复CHECK
     *
     * @param healthCycle
     * @return
     */
    @RequestMapping("health/checkCycleName")
    @ResponseBody
    public Boolean checkCycleName(HealthCycle healthCycle) {

        // 按名称检索 (LIKE检索)
        HealthCycle selectCycle = new HealthCycle();
        selectCycle.setPageSwitch(false);
        selectCycle.setCycleName(healthCycle.getCycleName());
        List<HealthCycle> cycleList = healthCycleMapper.selectListByCondition(selectCycle);
        // 没有名称类似的（LIKE）
        if (cycleList.size() == 0) {
            return true;
        }

        for (HealthCycle dbHealthCycle :cycleList) {
            // 当前名称和其他的记录的名称有相同时
            if (dbHealthCycle.getCycleName().equals(healthCycle.getCycleName())) {
                // 添加时
                if (healthCycle.getCycleId() == null) {
                    return false;
                } else {
                    // 修改时, 重名数据不是当前修改的记录
                    if (dbHealthCycle.getCycleId().intValue() != healthCycle.getCycleId().intValue()) {
                        return false;
                    }
                }
            }
        }

        return true;
    }


    /*****************************************体检套餐管理*****************************************************************************/
    /**
     * 体检套餐列表
     *
     * @param request
     * @return
     */
    @RequestMapping("health/pkgList")
    public ModelAndView healthPackageList(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("operation/health/pkgList");

        // 检索条件
        String pkgName = request.getParameter("pkgName");
        // 改页处理用
        String start = request.getParameter("start");

        HealthPackage healthPackage = new HealthPackage();
        if (StringUtils.isNotEmpty(pkgName)) {
            healthPackage.setPkgName(pkgName);
        }

        // 改页处理时
        if (StringUtils.isNotEmpty(start)) {
            healthPackage.setStart(Integer.valueOf(start));
        }

        List<HealthPackage> healthPackageList = healthPackageMapper.selectListByCondition(healthPackage);
        healthPackage.setResultList(healthPackageList);

        modelAndView.addObject("page", healthPackage);

        return modelAndView;
    }

    /**
     * 体检套餐增加
     *
     * @return
     */
    @RequestMapping(value = "health/toAddPkg")
    public ModelAndView toAddHealthPackage() {
        ModelAndView mv = new ModelAndView("operation/health/pkgAdd");

        return mv;
    }
    @RequestMapping(value = "health/doAddPkg")
    @ArchivesLog(operationDescription = "新增体检套餐")
    public ModelAndView doAddPackage(HealthPackage healthPackage) {
        ModelAndView mv = new ModelAndView("msg");

        // 默认套餐CHECK
        boolean errFlg = false;
        if ("1".equals(healthPackage.getIsDefault())) {
            // 按状态检索
            HealthPackage selectDefaultPkg = new HealthPackage();
            selectDefaultPkg.setPageSwitch(false);
            selectDefaultPkg.setIsDefault("1");
            List<HealthPackage> defaultPkgList = healthPackageMapper.selectListByCondition(selectDefaultPkg);
            // 有状态相同的时
            if (defaultPkgList != null && defaultPkgList.size() > 0) {
                // 添加时
                if (healthPackage.getPkgId() == null) {
                    errFlg = true;
                }
            }

            if (errFlg) {
                mv.addObject("msg", "最多只能有一个默认套餐,请重新设定");
                //返回到添加页面  mv.addObject("returnUrl", "operation/health/pkgList");
                return mv;
            }
        }

        // 套餐新增
        int inserCount = healthPackageMapper.insert(healthPackage);
        if (inserCount > 0) {
            mv.addObject("msg", "体检套餐新增成功");
        } else {
            mv.addObject("msg", "体检套餐新增失败");
        }
        mv.addObject("returnUrl", "operation/health/pkgList");

        return mv;
    }

    /**
     * 体检套餐修改
     *
     * @param pkgId
     * @return
     */
    @RequestMapping(value = "health/toEditPkg")
    public ModelAndView toModifyPackage(Integer pkgId) {
        ModelAndView mv = new ModelAndView("operation/health/pkgEdit");

        HealthPackage healthPackage = healthPackageMapper.selectByPrimaryKey(pkgId);
        mv.addObject("healthPkg", healthPackage);
        return mv;
    }
    @RequestMapping(value = "health/doEditPkg")
    @ArchivesLog(operationDescription = "修改体检套餐")
    public ModelAndView doModifyHealthPackage(HealthPackage healthPackage) {
        ModelAndView mv = new ModelAndView("msg");

        // 默认套餐CHECK
        boolean errFlg = false;
        if ("1".equals(healthPackage.getIsDefault())) {
            // 按是否默认套餐检索
            HealthPackage selectDefaultPkg = new HealthPackage();
            selectDefaultPkg.setPageSwitch(false);
            selectDefaultPkg.setIsDefault("1");
            List<HealthPackage> defaultPkgList = healthPackageMapper.selectListByCondition(selectDefaultPkg);
            // 有是否默认套餐相同的时
            if (defaultPkgList != null && defaultPkgList.size() > 0) {
                // 修改时
                if (healthPackage.getPkgId() != null) {
                    for (HealthPackage dbHealthPkg :defaultPkgList) {
                        // CHECK数据不是当前修改的记录
                        if (dbHealthPkg.getPkgId().intValue() != healthPackage.getPkgId().intValue()) {
                            errFlg = true;
                            break;
                        }
                    }
                }
            }

            if (errFlg) {
                mv.addObject("msg", "最多只能有一个默认套餐,请重新设定");
                //返回到添加页面  mv.addObject("returnUrl", "operation/health/pkgList");
                return mv;
            }
        }

        int updateCount = healthPackageMapper.updateByPrimaryKey(healthPackage);
        if (updateCount > 0) {
            mv.addObject("msg", "体检套餐修改成功");
        } else {
            mv.addObject("msg", "体检套餐修改失败");
        }
        mv.addObject("returnUrl", "operation/health/pkgList");

        return mv;
    }

    /**
     * 体检套餐删除
     *
     * @param request
     * @return
     */
    @RequestMapping("health/deletePkg")
    @ArchivesLog(operationDescription = "删除体检套餐")
    public ModelAndView deleteHealthPkg(HttpServletRequest request) {
        String[] id = request.getParameterValues("pkgId");

        ModelAndView mv = new ModelAndView("msg");

        int delFlg = healthPackageService.deleteHealthPackage(id);
        if (delFlg ==  1) {
            mv.addObject("msg", "体检套餐删除成功");
        } else {
            mv.addObject("msg", "体检套餐删除失败");
        }
        mv.addObject("returnUrl", "operation/health/pkgList");

        return mv;
    }

    /**
     *  体检套餐名称重复CHECK
     *
     * @param healthPkg
     * @return
     */
    @RequestMapping("health/checkPkgName")
    @ResponseBody
    public Boolean checkHealthPkgName(HealthPackage healthPkg) {

        // 名称重复CHECK不区分是否启用。。

        // 按名称检索 (LIKE检索)
        HealthPackage selectCycle = new HealthPackage();
        selectCycle.setPageSwitch(false);
        selectCycle.setPkgName(healthPkg.getPkgName());
        List<HealthPackage> pkgList = healthPackageMapper.selectListByCondition(selectCycle);
        // 没有名称类似的（LIKE）
        if (pkgList == null || pkgList.size() == 0) {
            return true;
        }

        for (HealthPackage dbHealthPackage :pkgList) {
            // 当前名称和其他的记录的名称有相同时
            if (dbHealthPackage.getPkgName().equals(healthPkg.getPkgName())) {
                // 添加时
                if (healthPkg.getPkgId() == null) {
                    return false;
                } else {
                    // 修改时, 重名数据不是当前修改的记录
                    if (dbHealthPackage.getPkgId().intValue() != healthPkg.getPkgId().intValue()) {
                        return false;
                    }
                }
            }
        }

        return true;
    }


    /*****************************************体检业务单元管理管理*****************************************************************************/
    /**
     * 业务单元列表
     *
     * @param request
     * @return
     */
    @RequestMapping("health/deptmentList")
    public ModelAndView healthDeptmentList(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("operation/health/deptList");

        // 检索条件
        String deptName = request.getParameter("deptName");
        // 改页处理用
        String start = request.getParameter("start");

        HealthDept healthDeptment = new HealthDept();
        if (StringUtils.isNotEmpty(deptName)) {
            healthDeptment.setDeptName(deptName);
        }

        // 改页处理时
        if (StringUtils.isNotEmpty(start)) {
            healthDeptment.setStart(Integer.valueOf(start));
        }

        // 体检机构的取得
        List<HealthDept> healthDeptmentList = healthDeptMapper.selectListByCondition(healthDeptment);
        for(HealthDept dept: healthDeptmentList) {
            String orgIds = dept.getOrgIds();
            List<HealthOrg> orgList = new ArrayList<HealthOrg>();
            if (!StringUtils.isBlank(orgIds)) {
                String[] orgIdArray = orgIds.split(",");
                for(String orgId: orgIdArray) {
                    HealthOrg healthOrg = healthOrgMapper.selectByPrimaryKey(Integer.valueOf(orgId));
                    orgList.add(healthOrg);
                }
            }
            dept.setOrgList(orgList);
        }

        healthDeptment.setResultList(healthDeptmentList);

        modelAndView.addObject("page", healthDeptment);

        return modelAndView;
    }

    /**
     * 业务单元增加
     *
     * @return
     */
    @RequestMapping(value = "health/toAddDeptment")
    public ModelAndView toAddHealthDeptment() {
        ModelAndView mv = new ModelAndView("operation/health/deptAdd");

        // 可选择体检机构的取得
        HealthOrg healthOrg = new HealthOrg();
        healthOrg.setPageSwitch(false);
        healthOrg.setOrgState(true);
        List<HealthOrg> healthOrgList = healthOrgMapper.selectListByCondition(healthOrg);
        mv.addObject("orgList", healthOrgList);

        return mv;
    }

    @RequestMapping(value = "health/doAddDeptment")
    @ArchivesLog(operationDescription = "新增业务单元")
    public ModelAndView doAddHealthDeptment(HealthDept healthDeptment) {
        ModelAndView mv = new ModelAndView("msg");

        int i = healthDeptMapper.insert(healthDeptment);
        if (i > 0) {
            mv.addObject("msg", "业务单元新增成功");
        } else {
            mv.addObject("msg", "业务单元新增失败");
        }
        mv.addObject("returnUrl", "operation/health/deptmentList");
        return mv;
    }

    /**
     * 业务单元修改
     *
     * @param deptId
     * @return
     */
    @RequestMapping(value = "health/toEditDeptment")
    public ModelAndView toModifyHealthDeptment(Integer deptId) {
        ModelAndView mv = new ModelAndView("operation/health/deptEdit");

        HealthDept healthDeptment = healthDeptMapper.selectByPrimaryKey(deptId);
        mv.addObject("healthDeptment", healthDeptment);

        // 可选择体检机构的取得
        HealthOrg healthOrg = new HealthOrg();
        healthOrg.setPageSwitch(false);
        healthOrg.setOrgState(true);
        List<HealthOrg> healthOrgList = healthOrgMapper.selectListByCondition(healthOrg);
        mv.addObject("orgList", healthOrgList);

        return mv;
    }

    @RequestMapping(value = "health/doEditDeptment")
    @ArchivesLog(operationDescription = "修改业务单元")
    public ModelAndView doModifyHealthDeptment(HealthDept healthDeptment) {
        ModelAndView mv = new ModelAndView("msg");
        // 全项目更新
        int i = healthDeptMapper.updateByPrimaryKey(healthDeptment);
        if (i > 0) {
            mv.addObject("msg", "业务单元修改成功");
        } else {
            mv.addObject("msg", "业务单元修改失败");
        }
        mv.addObject("returnUrl", "operation/health/deptmentList");

        return mv;
    }

    /**
     * 业务单元删除
     *
     * @param request
     * @return
     */
    @RequestMapping("health/deleteDeptment")
    @ArchivesLog(operationDescription = "删除业务单元")
    public ModelAndView deleteHealthDeptment(HttpServletRequest request) {
        String[] deptIds = request.getParameterValues("deptId");

        ModelAndView mv = new ModelAndView("msg");

        int i = healthDeptmentService.deleteHealthDeptment(deptIds);
        if (i ==  1) {
            mv.addObject("msg", "业务单元删除成功");
        } else {
            mv.addObject("msg", "业务单元删除失败");
        }
        mv.addObject("returnUrl", "operation/health/deptmentList");

        return mv;
    }

    /**
     *  业务单元重名CHECK
     *
     * @param healthDeptment
     * @return
     */
    @RequestMapping("health/checkDeptName")
    @ResponseBody
    public Boolean checkDeptName(HealthDept healthDeptment) {

        // 按名称检索 (LIKE检索)
        HealthDept selectDeptment = new HealthDept();
        selectDeptment.setPageSwitch(false);
        selectDeptment.setDeptName(healthDeptment.getDeptName());
        List<HealthDept> deptmentList = healthDeptMapper.selectListByCondition(selectDeptment);
        // 没有名称类似的（LIKE）
        if (deptmentList.size() == 0) {
            return true;
        }

        //  由于名称是LIKE检索，因此需要判断是否完全一致
        for (HealthDept dbDeptment :deptmentList) {
            // 当前名称和其他的记录的名称有相同时
            if (dbDeptment.getDeptName().equals(healthDeptment.getDeptName())) {
                // 添加时
                if (healthDeptment.getDeptId() == null) {
                    return false;
                } else {
                    // 修改时, 重名数据不是当前修改的记录
                    if (dbDeptment.getDeptId().intValue() != healthDeptment.getDeptId().intValue()) {
                        return false;
                    }
                }
            }
        }

        // 添加的数据没有重名的
        // 修改后的数据没有重名的，或者修改的是当前记录的数据
        return true;
    }


    /**
     * 业务单元文件导入
     *
     * @param multipartRequeste
     * @return
     */
    @RequestMapping(value = "health/deptFileUpload")
    @ResponseBody
    public String deptFileUpload(MultipartHttpServletRequest multipartRequeste){

        Iterator<Map.Entry<String,MultipartFile>> it =  multipartRequeste.getFileMap().entrySet().iterator();

        if (!it.hasNext()) {
            return "没有选择导入文件";
        }

        // 文件上传
        MultipartFile multipartFile = it.next().getValue();
        String extName = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
        String tempDir = System.getProperty("user.dir");
        String name = new Date().getTime() + extName.toLowerCase();
        String filName = tempDir.concat(File.separator).concat(name);
        File targetFile = new File(filName);

        try {
            multipartFile.transferTo(targetFile);
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败";
        }

        // 文件内容的读取
        Map<Integer, Map<Integer, String>> mapContent = null;
        try {
            mapContent = ExcelUtil.readExcelContent(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
            return "文件读取失败";
        }

        if (mapContent.size() <= 1) {
            return "文件内没有数据";
        }

        // 可选择体检机构的取得
        HealthOrg healthOrg = new HealthOrg();
        healthOrg.setPageSwitch(false);
        healthOrg.setOrgState(true);
        List<HealthOrg> healthOrgList = healthOrgMapper.selectListByCondition(healthOrg);
        Map<String, Integer> healthOrgMap = new HashMap<String, Integer>();
        for (HealthOrg healthOrgTemp: healthOrgList) {
            healthOrgMap.put(healthOrgTemp.getOrgName(), healthOrgTemp.getOrgId());
        }

        // 文件数据的设定
        // 错误信息列表
        List<String> errorList = new ArrayList<String>();
        String errMsg = null;
        // 业务单元数据
        List<HealthDept> healthDeptList = new ArrayList<HealthDept>();
        HealthDept healthDept = null;
        // 列编号
        int colIndex = 0;
        String strCell = null;
        // 第一行为标题
        for (int i = 1; i < mapContent.size(); i++) {
            Map<Integer, String> rowContent = mapContent.get(i);

            // 业务单元信息的设定
            healthDept = new HealthDept();
            errMsg = "";

            // 序号
            colIndex = 0;
            strCell = rowContent.get(colIndex);
            if (strCell == null || "".equals(strCell.trim())) {
                break;
            }

            // 业务单元名称
            colIndex = colIndex + 1;
            strCell = rowContent.get(colIndex);
            if (StringUtils.isBlank(strCell)) {
                errMsg = errMsg.concat("业务单元名称不能为空、");
            } else {
                healthDept.setDeptName(strCell.trim());
            }

            // 业务单元负责人
            colIndex = colIndex + 1;
            strCell = rowContent.get(colIndex);
            if (StringUtils.isBlank(strCell)) {
                // 不设定
            } else {
                healthDept.setDeptPrincipal(strCell.trim());
            }

            // 体检机构
            colIndex = colIndex + 1;
            strCell = rowContent.get(colIndex);
            if (StringUtils.isBlank(strCell)) {
                // 不设定
            } else {
                String orgIds = "";
                String orgNames = strCell.trim();
                String[] orgNameArray = orgNames.split(",");
                for (String orgName: orgNameArray) {
                    if (StringUtils.isBlank(orgIds)) {
                        orgIds = healthOrgMap.get(orgName) + "";
                    } else {
                        orgIds = orgIds + "," + healthOrgMap.get(orgName);
                    }
                }

                healthDept.setOrgIds(orgIds);
            }

            // 重复check判断用
            healthDeptList.add(healthDept);

            // 错误信息有无的判断
            if (!"".equals(errMsg.trim())) {
                errMsg = errMsg.substring(0, errMsg.length()-1);
                errMsg = "第" + i + "条数据的错误信息：" + errMsg;
                errorList.add(errMsg);
                continue;
            }
        }

        // 临时文件的删除
        final String fullname = filName;
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                new File(fullname).delete();
            }
        }, 10000);

        // 数据文件内重复数据的判断
        HealthDept healthDept1 = null;
        HealthDept healthDept2 = null;
        for (int i = 0; i<healthDeptList.size(); i++) {
            healthDept1 = healthDeptList.get(i);
            for (int j = i+1; j<healthDeptList.size(); j++) {
                healthDept2 = healthDeptList.get(j);
                errMsg = "";

                if (StringUtils.isNotEmpty(healthDept1.getDeptName()) && StringUtils.isNotEmpty(healthDept2.getDeptName())) {
                    if (healthDept1.getDeptName().equals(healthDept2.getDeptName())) {
                        errMsg = errMsg + "业务单元名称相同。";
                    }
                }

                if (!"".equals(errMsg.trim())) {
                    errMsg = errMsg.substring(0, errMsg.length()-1);
                    errMsg = "第" + (i+1) + "条数据和第" + (j+1) + "条数据的" + errMsg;
                    errorList.add(errMsg);
                }
            }
        }

        // 有错误信息时
        if (errorList.size() > 0) {
            String jsonStr = "ERROR_LIST:" + JSON.toJSONString(errorList);
            return jsonStr;
        }

        // 数据导入
        AjaxReturnData ajaxReturnData = healthDeptmentService.addHealthDeptList(healthDeptList);

        // ajaxReturnData.Result = false --->> 数据库内有业务单元名称相同的数据
        // ajaxReturnData.Result = true --->> 导入成功
        return ajaxReturnData.getMessage();
    }

    /*****************************************体检用户管理*****************************************************************************/
    /**
     *  体检用户信息页面显示
     *  体检用户信息一览
     *
     * @param request
     *
     * @return
     */
    @AuthPassport
    @RequestMapping(value = "health/userList")
    public ModelAndView healthUserList(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("operation/health/userList");

        // 检索条件
        String orgId = request.getParameter("orgId");
        String state = request.getParameter("state");
        String startCheckDate = request.getParameter("startCheckDate");
        String endCheckDate = request.getParameter("endCheckDate");
        String userName = request.getParameter("userName");
        String deptId = request.getParameter("deptId");
        // 登录者自己部门的检索条件
        MemberBase memberBase = (MemberBase)request.getSession().getAttribute("memInfo");
        if (memberBase != null && memberBase.getHealthDeptId() != null ) {
            deptId = String.valueOf(memberBase.getHealthDeptId());
        }
        String startCancelTime = request.getParameter("startCancelTime");
        String endCancelTime = request.getParameter("endCancelTime");
        String mobPhone = request.getParameter("mobPhone");
        String cardId = request.getParameter("cardId");
        String startAppointmentTime = request.getParameter("startAppointmentTime");
        String endAppointmentTime = request.getParameter("endAppointmentTime");

        //用户信息查询
        HealthUser healthUserSearch = new HealthUser();
        // 改页处理用
        String start = request.getParameter("start");
        if (StringUtils.isNotEmpty(start)) {
            healthUserSearch.setStart(Integer.valueOf(start));
        }
        //用户信息条件
        healthUserSearch.setState(state);
        healthUserSearch.setUserName(userName);
        if (StringUtils.isNotEmpty(deptId)) {
            healthUserSearch.setDeptId(Integer.valueOf(deptId));
        }
        healthUserSearch.setMobPhone(mobPhone);
        healthUserSearch.setCardId(cardId);
        //预约信息条件
        if (StringUtils.isNotEmpty(orgId)) {
            healthUserSearch.setUaOrgId(Integer.valueOf(orgId));
        }
        healthUserSearch.setUaStartAppointmentTime(startAppointmentTime);
        healthUserSearch.setUaEndAppointmentTime(endAppointmentTime);
        healthUserSearch.setUaStartCheckDate(startCheckDate);
        healthUserSearch.setUaEndCheckDate(endCheckDate);
        healthUserSearch.setUaStartCancelTime(startCancelTime);
        healthUserSearch.setUaEndCancelTime(endCancelTime);
        //查询结果
        List<HealthUser> healthUserList = healthUserMapper.searchListByCondition(healthUserSearch);
        healthUserSearch.setResultList(healthUserList);

        // 可选择体检机构的取得
        HealthOrg healthOrg= new HealthOrg();
        healthOrg.setPageSwitch(false);
        List<HealthOrg> healthOrgList = healthOrgMapper.selectListByCondition(healthOrg);
        view.addObject("orgList", healthOrgList);
        // 可选择业务单元的取得
        HealthDept healthDept= new HealthDept();
        healthDept.setPageSwitch(false);
        List<HealthDept> healthDeptList = healthDeptMapper.selectListByCondition(healthDept);
        view.addObject("deptList", healthDeptList);
        //查询结果
        view.addObject("page", healthUserSearch);
        view.addObject("memberBase", memberBase);
        //查询条件
        view.addObject("orgId", orgId);
        view.addObject("state", state);
        view.addObject("startCheckDate", startCheckDate);
        view.addObject("endCheckDate", endCheckDate);
        view.addObject("userName", userName);
        view.addObject("deptId", deptId);
        view.addObject("startCancelTime", startCancelTime);
        view.addObject("endCancelTime", endCancelTime);
        view.addObject("mobPhone", mobPhone);
        view.addObject("cardId", cardId);
        view.addObject("startAppointmentTime", startAppointmentTime);
        view.addObject("endAppointmentTime", endAppointmentTime);
        return view;
    }

    /**
     *  导出体检用户信息页面显示
     *
     * @return
     */
    @RequestMapping(value = "health/exportUserList")
    public ModelAndView exportUserList() {
        ModelAndView view = new ModelAndView("operation/health/userList_export");
        // 可选择体检机构的取得
        HealthOrg healthOrg = new HealthOrg();
        healthOrg.setPageSwitch(false);
        List<HealthOrg> healthOrgList = healthOrgMapper.selectListByCondition(healthOrg);
        view.addObject("orgList", healthOrgList);
        return view;
    }

    /**
     * 用户文件导出
     *
     * @param request
     * @return
     */
    @RequestMapping("health/userListExport")
    @ResponseBody
    public AjaxReturnData userListExport(HttpServletRequest request) {

        AjaxReturnData ajaxReturnData = new AjaxReturnData();

        try {
            // 导出预约名单按钮/导出取消名单按钮
            String btnFlg = request.getParameter("btnFlg");
            // 检索条件
            String orgId = request.getParameter("orgId");
            String startTime = request.getParameter("startTime");
            String endTime = request.getParameter("endTime");
            //用户预约信息查询
            HealthUserAppointment huaSearch = new HealthUserAppointment();
            huaSearch.setPageSwitch(false);
            huaSearch.setBtnFlg(btnFlg);
            huaSearch.setOrgId(Integer.valueOf(orgId));
            huaSearch.setStartTime(startTime + ":00");
            huaSearch.setEndTime(endTime + ":00");
            //查询结果
            List<HealthUserAppointment> huaList = healthUserAppointmentMapper.exportListByCondition(huaSearch);

            // 导出EXCEL的设定
            HSSFWorkbook workbook = new HSSFWorkbook();
            //新建sheet页
            HSSFSheet sheet = workbook.createSheet("标签");

            int rowIndex = 0;
            int colIndex = 0;

            // 大标题
            HSSFRow row = sheet.createRow(rowIndex++);
            // 设置字体
            CellStyle style0 = workbook.createCellStyle();
            HSSFFont font0 = workbook.createFont();
            font0.setFontName("黑体");
            font0.setFontHeightInPoints((short) 18);//设置字体大小
            font0.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示
            style0.setAlignment(CellStyle.ALIGN_CENTER);
            style0.setFont(font0);
            HSSFCell cell;
            for (int i = 0; i < 14; i++) {
                cell = row.createCell(i);
                if (i == 0) {
                    cell.setCellValue("2023年员工健康体检报名表");
                    cell.setCellStyle(style0);
                }
            }
            CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, 13);
            sheet.addMergedRegion(cellRangeAddress);


            // 标题
            row = sheet.createRow(rowIndex++);

            String[] titleName = { "序号", "部门", "姓名", "性别", "年龄", "手机号",
                    "身份证号", "套餐类型", "必选项目", "自选项目", "体检机构", "预约日期"};
             //列宽(自适应宽度用)
            int[] colWidth = {1025, 4050, 2050, 1025, 1025, 4050,
                    5050, 3075, 2050, 4050, 6050, 2050};

            // 设置字体
            CellStyle style = workbook.createCellStyle();
            HSSFFont font = workbook.createFont();
            font.setFontName("宋体");
            font.setFontHeightInPoints((short) 12);//设置字体大小
            style.setAlignment(CellStyle.ALIGN_CENTER);
            style.setFont(font);

            for (int i = 0; i < titleName.length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(titleName[i]);
                cell.setCellStyle(style);

                // 每一列中的最大值乘一个系数(汉字是512，数字是256.)
                int length = titleName[i].length();
                if (length > colWidth[i] / 512) {     // 列宽
                    colWidth[i] = length * 512;
                }
            }

            if (huaList != null && huaList.size() > 0) {
                for (HealthUserAppointment huaInfo : huaList) {
                    // 用户信息查询
                    HealthUser healthUserSearch = new HealthUser();
                    healthUserSearch.setPageSwitch(false);
                    healthUserSearch.setUserId(huaInfo.getUserId());
                    List<HealthUser> healthUserList = healthUserMapper.selectListByCondition(healthUserSearch);
                    HealthUser healthUserTemp = new HealthUser();
                    if (healthUserList != null && healthUserList.size() > 0) {
                        healthUserTemp = healthUserList.get(0);
                    } else {
                        continue;
                    }

                    row = sheet.createRow(rowIndex++);
                    colIndex = 0;

                    // 序号
                    if (String.valueOf(colIndex).length() > colWidth[colIndex] / 256) {     // 列宽
                        colWidth[colIndex] = String.valueOf(colIndex).length() * 256;
                    }
                    cell = row.createCell(colIndex++);
                    cell.setCellValue(rowIndex-2);
                    cell.setCellStyle(style);

                    // 业务单元名称（所属部门）
                    cell = row.createCell(colIndex++);
                    if (StringUtils.isNotEmpty(healthUserTemp.getDeptName())) {
                        if (healthUserTemp.getDeptName().length() > colWidth[colIndex-1] / 512) {     // 列宽
                            colWidth[colIndex-1] = healthUserTemp.getDeptName().length() * 512;
                        }
                        cell.setCellValue(healthUserTemp.getDeptName());
                    }
                    cell.setCellStyle(style);
                    // 用户姓名
                    cell = row.createCell(colIndex++);
                    if (StringUtils.isNotEmpty(healthUserTemp.getUserName())) {
                        if (healthUserTemp.getUserName().length() > colWidth[colIndex-1] / 512) {     // 列宽
                            colWidth[colIndex-1] = healthUserTemp.getUserName().length() * 512;
                        }
                        cell.setCellValue(healthUserTemp.getUserName());
                    }
                    cell.setCellStyle(style);
                    // 性别
                    cell = row.createCell(colIndex++);
                    if (StringUtils.isNotEmpty(healthUserTemp.getUserSex())) {
                        String userSex = "";
                        // 性别 1:男 2:女
                        if ("1".equals(healthUserTemp.getUserSex())) {
                            userSex = "男";
                        } else if ("2".equals(healthUserTemp.getUserSex())) {
                            userSex = "女";
                        }
                        if (userSex.length() > colWidth[colIndex-1] / 512) {     // 列宽
                            colWidth[colIndex-1] = userSex.length() * 512;
                        }
                        cell.setCellValue(userSex);
                    }
                    cell.setCellStyle(style);
                    // 年龄
                    cell = row.createCell(colIndex++);
                    if(healthUserTemp.getUserAge() != null) {
                        cell.setCellValue(healthUserTemp.getUserAge());
                    }
                    cell.setCellStyle(style);
                    // 手机号码
                    cell = row.createCell(colIndex++);
                    if (StringUtils.isNotEmpty(healthUserTemp.getMobPhone())) {
                        if (healthUserTemp.getMobPhone().length() > colWidth[colIndex-1] / 256) {     // 列宽
                            colWidth[colIndex-1] = healthUserTemp.getMobPhone().length() * 256;
                        }
                        cell.setCellValue(healthUserTemp.getMobPhone());
                    }
                    cell.setCellStyle(style);
                    // 身份证号
                    cell = row.createCell(colIndex++);
                    if (StringUtils.isNotEmpty(healthUserTemp.getCardId())) {
                        if (StringUtils.isNotEmpty(healthUserTemp.getCardId())) {
                            if (healthUserTemp.getCardId().length() > colWidth[colIndex-1] / 256) {     // 列宽
                                colWidth[colIndex-1] = healthUserTemp.getCardId().length() * 256;
                            }
                            cell.setCellValue(healthUserTemp.getCardId());
                        }
                    }
                    cell.setCellStyle(style);
//                    // 有无胸部CT检查
//                    cell = row.createCell(colIndex++);
//                    if (StringUtils.isNotEmpty(huaInfo.getPkgType())) {
//                        String pkgType = "";
//                        // 根据套餐类型表的主键判断
//                        // 有无胸部CT检查 1:无胸部CT检查 3:有胸部CT检查
//                        if (!"1".equals(huaInfo.getPkgType())) {
//                            pkgType = "有";
//                        }
//                        if (pkgType.length() > colWidth[colIndex-1] / 512) {     // 列宽
//                            colWidth[colIndex-1] = pkgType.length() * 512;
//                        }
//                        cell.setCellValue(pkgType);
//                    }
//                    // 升级套餐
//                    cell = row.createCell(colIndex++);
//                    if (StringUtils.isNotEmpty(healthUserTemp.getPkgUpgrade())) {
//                        String pkgUpgrade = "";
//                        // 升级套餐 1:是 0:否
//                        if ("1".equals(healthUserTemp.getPkgUpgrade())) {
//                            pkgUpgrade = "是";
//                        }
//                        if (pkgUpgrade.length() > colWidth[colIndex-1] / 512) {     // 列宽
//                            colWidth[colIndex-1] = pkgUpgrade.length() * 512;
//                        }
//                        cell.setCellValue(pkgUpgrade);
//                    }
                    // 用户预约信息
                    // 套餐类型
                    cell = row.createCell(colIndex++);
                    if(StringUtils.isNotEmpty(huaInfo.getPkgType())) {
                        if (huaInfo.getPkgType().length() > colWidth[colIndex-1] / 512) {     // 列宽
                            colWidth[colIndex-1] = huaInfo.getPkgType().length() * 512;
                        }
                        cell.setCellValue(huaInfo.getPkgType());
                    }
                    cell.setCellStyle(style);
//                    // 心肺功能专项
//                    cell = row.createCell(colIndex++);
//                    if ("是".length() > colWidth[colIndex-1] / 512) {     // 列宽
//                        colWidth[colIndex-1] = "是".length() * 512;
//                    }
//                    if("是".equals(huaInfo.getCardiopulmonaryFunctionCheckOption())) {
//                        cell.setCellValue("是");
//                    } else {
//                        cell.setCellValue("");
//                    }
//                    cell.setCellStyle(style);

//                    // 胸部CT套餐
//                    cell = row.createCell(colIndex++);
//                    if ("无胸部CT".length() > colWidth[colIndex-1] / 512) {     // 列宽
//                        colWidth[colIndex-1] = "无胸部CT".length() * 512;
//                    }
//                    if(StringUtils.isNotEmpty(huaInfo.getBreastCT())) {
//                        cell.setCellValue(huaInfo.getBreastCT());
//                    } else if (StringUtils.isNotEmpty(huaInfo.getRequiredOption())) {
//                        if (huaInfo.getRequiredOption().contains("胸部CT")) {
//                            cell.setCellValue("有胸部CT");
//                        } else if (StringUtils.equals(huaInfo.getRequiredOption(), "⑤无核磁")) {
//                            cell.setCellValue("有胸部CT");
//                        } else {
//                            cell.setCellValue("无胸部CT");
//                        }
//                    }

//                    // 如果当前套餐类型为C，并且选择的体检机构是北京电力医院(含无痛胃肠镜)、北京电力医院(不含无痛胃肠镜)、北京航天中心医院(含无痛胃肠镜)、北京航天中心医院(不含无痛胃肠镜)
//                    if (StringUtils.equals(huaInfo.getPkgType(), "C1") || StringUtils.equals(huaInfo.getPkgType(), "C2")
//                            || StringUtils.equals(huaInfo.getPkgType(), "C3") || StringUtils.equals(huaInfo.getPkgType(), "C4")) {
//                        if (StringUtils.equals(huaInfo.getOrgName(), "北京电力医院(含无痛胃肠镜)") || StringUtils.equals(huaInfo.getOrgName(), "北京电力医院(不含无痛胃肠镜)")
//                                || StringUtils.equals(huaInfo.getOrgName(), "北京航天中心医院(含无痛胃肠镜)") || StringUtils.equals(huaInfo.getOrgName(), "北京航天中心医院(不含无痛胃肠镜)")) {
//                            cell.setCellValue("有胸部CT");
//                        }
//                    }
//                    // 如果当前套餐类型为B，则一定是"有胸部CT"
//                    if (StringUtils.equals(huaInfo.getPkgType(), "B1") || StringUtils.equals(huaInfo.getPkgType(), "B2")) {
//                        cell.setCellValue("有胸部CT");
//                    }
//                    cell.setCellStyle(style);

                    // 必选项目
                    cell = row.createCell(colIndex++);
                    if(StringUtils.isNotEmpty(huaInfo.getRequiredOption())) {
                        if (huaInfo.getRequiredOption().length() > colWidth[colIndex-1] / 512) {     // 列宽
                            colWidth[colIndex-1] = huaInfo.getRequiredOption().length() * 512;
                        }
                        cell.setCellValue(huaInfo.getRequiredOption().substring(0, 1));
                    }
                    cell.setCellStyle(style);
                    // 自选项目
                    cell = row.createCell(colIndex++);
                    if ("有".length() > colWidth[colIndex-1] / 512) {     // 列宽
                        colWidth[colIndex-1] = "有".length() * 512;
                    }
                    if(StringUtils.isNotEmpty(huaInfo.getOptionalOption())) {
                        cell.setCellValue("有");
                    } else {
                        cell.setCellValue("");
                    }
                    cell.setCellStyle(style);
                    // 预约体检机构
                    cell = row.createCell(colIndex++);
                    if(StringUtils.isNotEmpty(huaInfo.getOrgName())) {
                        if (huaInfo.getOrgName().length() > colWidth[colIndex-1] / 512) {     // 列宽
                            colWidth[colIndex-1] = huaInfo.getOrgName().length() * 512;
                        }
                        cell.setCellValue(huaInfo.getOrgName());
                    }
                    cell.setCellStyle(style);
                    // 预约体检时间
                    cell = row.createCell(colIndex++);
                    if(StringUtils.isNotEmpty(huaInfo.getCheckDateStr())) {
                        if (huaInfo.getCheckDateStr().length() > colWidth[colIndex-1] / 512) {     // 列宽
                            colWidth[colIndex-1] = huaInfo.getCheckDateStr().length() * 512;
                        }
                        cell.setCellValue(huaInfo.getCheckDateStr());
                    }
                    cell.setCellStyle(style);
//                    // 心理健康评测
//                    cell = row.createCell(colIndex++);
//                    if ("是".length() > colWidth[colIndex-1] / 512) {     // 列宽
//                        colWidth[colIndex-1] = "是".length() * 512;
//                    }
//                    if("是".equals(huaInfo.getPsychologicalAssessmentCheckOption())) {
//                        cell.setCellValue("是");
//                    } else {
//                        cell.setCellValue("");
//                    }
//                    cell.setCellStyle(style);
                }
            }

            // 自适应列宽度
            for (int i = 0; i < titleName.length; i++) {
                sheet.setColumnWidth(i, colWidth[i]);
            }

            // 去掉UUID 的 -
            String filename = UUID.randomUUID().toString().replaceAll("-", "") + ".xls";

            String dir = request.getSession().getServletContext().getRealPath("/").concat(File.separator).concat("temp").concat(File.separator);
            File file = new File(dir);
            if (!file.exists()) {
                file.mkdirs();
            }

            final String fullname = dir + filename;
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    new File(fullname).delete();
                }
            }, 600000);

            OutputStream os = new FileOutputStream(fullname);
            workbook.write(os);
            os.flush();
            os.close();

            ajaxReturnData.setResult(true);
            ajaxReturnData.setReturnStr(filename);

        } catch (Exception e) {
            ajaxReturnData.setResult(false);
            e.printStackTrace();
            logger.error(e.getLocalizedMessage());
        }
        return ajaxReturnData;
    }

//    /**
//     * 用户文件导出
//     *
//     * @param request
//     * @return
//     */
//    @RequestMapping("health/userListExport")
//    @ResponseBody
//    public AjaxReturnData userListExport(HttpServletRequest request) {
//
//        AjaxReturnData ajaxReturnData = new AjaxReturnData();
//
//        try {
//            // 检索条件
//            String orgId = request.getParameter("orgId");
//            String exportTime = request.getParameter("exportTime");
//            String startCheckDate = "";
//            String endCheckDate = "";
//            if ("1".equals(exportTime)) {
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                Calendar calendar1 = Calendar.getInstance();
//                calendar1.add(Calendar.DATE, 1);
//                startCheckDate = sdf.format(calendar1.getTime());
//
//                Calendar calendar2 = Calendar.getInstance();
//                calendar2.add(Calendar.DATE, 7);
//                endCheckDate = sdf.format(calendar2.getTime());
//            }
//            //用户预约信息查询
//            HealthUserAppointment huaSearch = new HealthUserAppointment();
//            huaSearch.setPageSwitch(false);
//            if (StringUtils.isNotEmpty(orgId)) {
//                huaSearch.setOrgId(Integer.valueOf(orgId));
//            }
//            if (StringUtils.isNotEmpty(startCheckDate)) {
//                huaSearch.setStartCheckDate(startCheckDate);
//            }
//            if (StringUtils.isNotEmpty(endCheckDate)) {
//                huaSearch.setEndCheckDate(endCheckDate);
//            }
//            //查询结果
//            List<HealthUserAppointment> huaList = healthUserAppointmentMapper.exportListByCondition(huaSearch);
//
//            // 导出EXCEL的设定
//            HSSFWorkbook workbook = new HSSFWorkbook();
//            //新建sheet页
//            HSSFSheet sheet = workbook.createSheet("userList");
//
//            int rowIndex = 0;
//            int colIndex = 0;
//
//            // 标题
//            HSSFRow row = sheet.createRow(rowIndex++);
//
//            String[] titleName = { "序号", "业务单元名称", "姓名", "性别", "年龄", "手机号",
//                    "身份证号", "套餐升级", "预约体检机构", "预约体检时间", "预约体检状态"};
//            // 列宽(自适应宽度用)
//            int[] colWidth = {1025, 4050, 2050, 1025, 1025, 3075, 3075, 2050, 4050, 2050, 2050};
//
//            // 设置字体
//            CellStyle style = workbook.createCellStyle();
//            HSSFFont font = workbook.createFont();
//            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//            style.setAlignment(CellStyle.ALIGN_CENTER);
//            style.setFont(font);
//
//            HSSFCell cell;
//            for (int i = 0; i < titleName.length; i++) {
//                cell = row.createCell(i);
//                cell.setCellValue(titleName[i]);
//                cell.setCellStyle(style);
//
//                // 每一列中的最大值乘一个系数(汉字是512，数字是256.)
//                int length = titleName[i].length();
//                if (length > colWidth[i] / 512) {     // 列宽
//                    colWidth[i] = length * 512;
//                }
//            }
//
//            if (huaList != null && huaList.size() > 0) {
//                //序号
//                int no = 0;
//                // 体检时间
//                String checkDateTemp = "";
//                for (HealthUserAppointment huaInfo : huaList) {
//                    //人员名单以日期为单位分开导出
//                    if (checkDateTemp.equals(huaInfo.getCheckDateStr()) == false) {
//                        if (StringUtils.isNotEmpty(checkDateTemp)) {
//                            row = sheet.createRow(rowIndex++);
//                        }
//                        row = sheet.createRow(rowIndex++);
//                        colIndex = 0;
//
//                        cell = row.createCell(colIndex++);
//                        cell.setCellValue("体检日期为" + huaInfo.getCheckDateStr() + "的人员名单如下：");
//                        //序号从1重新开始排序
//                        no = 0;
//                    }
//
//                    row = sheet.createRow(rowIndex++);
//                    colIndex = 0;
//
//                    // 序号
//                    if (String.valueOf(colIndex).length() > colWidth[colIndex] / 256) {     // 列宽
//                        colWidth[colIndex] = String.valueOf(colIndex).length() * 256;
//                    }
//                    cell = row.createCell(colIndex++);
//                    cell.setCellValue(no + 1);
//                    no++;
//
//                    // 用户信息查询
//                    HealthUser healthUserSearch = new HealthUser();
//                    healthUserSearch.setPageSwitch(false);
//                    healthUserSearch.setUserId(huaInfo.getUserId());
//                    List<HealthUser> healthUserList = healthUserMapper.selectListByCondition(healthUserSearch);
//                    HealthUser healthUserTemp = new HealthUser();
//                    if (healthUserList != null && healthUserList.size() > 0) {
//                        healthUserTemp = healthUserList.get(0);
//                    }
//                    // 业务单元名称（所属部门）
//                    cell = row.createCell(colIndex++);
//                    if (StringUtils.isNotEmpty(healthUserTemp.getDeptName())) {
//                        if (healthUserTemp.getDeptName().length() > colWidth[colIndex-1] / 512) {     // 列宽
//                            colWidth[colIndex-1] = healthUserTemp.getDeptName().length() * 512;
//                        }
//                        cell.setCellValue(healthUserTemp.getDeptName());
//                    }
//                    // 用户姓名
//                    cell = row.createCell(colIndex++);
//                    if (StringUtils.isNotEmpty(healthUserTemp.getUserName())) {
//                        if (healthUserTemp.getUserName().length() > colWidth[colIndex-1] / 512) {     // 列宽
//                            colWidth[colIndex-1] = healthUserTemp.getUserName().length() * 512;
//                        }
//                        cell.setCellValue(healthUserTemp.getUserName());
//                    }
//                    // 性别
//                    cell = row.createCell(colIndex++);
//                    if (StringUtils.isNotEmpty(healthUserTemp.getUserSex())) {
//                        String userSex = "";
//                        // 性别 1:男 2:女
//                        if ("1".equals(healthUserTemp.getUserSex())) {
//                            userSex = "男";
//                        } else if ("2".equals(healthUserTemp.getUserSex())) {
//                            userSex = "女";
//                        }
//                        if (userSex.length() > colWidth[colIndex-1] / 512) {     // 列宽
//                            colWidth[colIndex-1] = userSex.length() * 512;
//                        }
//                        cell.setCellValue(userSex);
//                    }
//                    // 年龄
//                    cell = row.createCell(colIndex++);
//                    if(healthUserTemp.getUserAge() != null) {
//                        cell.setCellValue(healthUserTemp.getUserAge());
//                    }
//                    // 手机号码
//                    cell = row.createCell(colIndex++);
//                    if (StringUtils.isNotEmpty(healthUserTemp.getMobPhone())) {
//                        if (healthUserTemp.getMobPhone().length() > colWidth[colIndex-1] / 256) {     // 列宽
//                            colWidth[colIndex-1] = healthUserTemp.getMobPhone().length() * 256;
//                        }
//                        cell.setCellValue(healthUserTemp.getMobPhone());
//                    }
//                    // 身份证号
//                    cell = row.createCell(colIndex++);
//                    if (StringUtils.isNotEmpty(healthUserTemp.getCardId())) {
//                        if (StringUtils.isNotEmpty(healthUserTemp.getCardId())) {
//                            if (healthUserTemp.getCardId().length() > colWidth[colIndex-1] / 256) {     // 列宽
//                                colWidth[colIndex-1] = healthUserTemp.getCardId().length() * 256;
//                            }
//                            cell.setCellValue(healthUserTemp.getCardId());
//                        }
//                    }
//                    // 升级套餐
//                    cell = row.createCell(colIndex++);
//                    if (StringUtils.isNotEmpty(healthUserTemp.getPkgUpgrade())) {
//                        String pkgUpgrade = "";
//                        // 性别 1:是 0:否
//                        if ("1".equals(healthUserTemp.getPkgUpgrade())) {
//                            pkgUpgrade = "是";
//                        }
//                        if (pkgUpgrade.length() > colWidth[colIndex-1] / 512) {     // 列宽
//                            colWidth[colIndex-1] = pkgUpgrade.length() * 512;
//                        }
//                        cell.setCellValue(pkgUpgrade);
//                    }
//                    // 用户预约信息
//                    // 预约体检机构
//                    cell = row.createCell(colIndex++);
//                    if(StringUtils.isNotEmpty(huaInfo.getOrgName())) {
//                        if (huaInfo.getOrgName().length() > colWidth[colIndex-1] / 512) {     // 列宽
//                            colWidth[colIndex-1] = huaInfo.getOrgName().length() * 512;
//                        }
//                        cell.setCellValue(huaInfo.getOrgName());
//                    }
//                    // 预约体检时间
//                    cell = row.createCell(colIndex++);
//                    if(StringUtils.isNotEmpty(huaInfo.getCheckDateStr())) {
//                        if (huaInfo.getCheckDateStr().length() > colWidth[colIndex-1] / 512) {     // 列宽
//                            colWidth[colIndex-1] = huaInfo.getCheckDateStr().length() * 512;
//                        }
//                        cell.setCellValue(huaInfo.getCheckDateStr());
//                    }
//                    // 预约体检状态
//                    String checkState = "";
//                    if(StringUtils.isNotEmpty(huaInfo.getCancelTimeStr())) {
//                        checkState = "已取消";
//                    } else {
//                        checkState = "已预约";
//                    }
//                    cell = row.createCell(colIndex++);
//                    if (checkState.length() > colWidth[colIndex-1] / 512) {     // 列宽
//                        colWidth[colIndex-1] = checkState.length() * 512;
//                    }
//                    cell.setCellValue(checkState);
//
//                    checkDateTemp = huaInfo.getCheckDateStr();
//                }
//
//                // 自适应列宽度
//                for (int i = 0; i < titleName.length; i++) {
//                    sheet.setColumnWidth(i, colWidth[i]);
//                }
//            }
//
//            // 去掉UUID 的 -
//            String filename = UUID.randomUUID().toString().replaceAll("-", "") + ".xls";
//
//            String dir = request.getSession().getServletContext().getRealPath("/").concat(File.separator).concat("temp").concat(File.separator);
//            File file = new File(dir);
//            if (!file.exists()) {
//                file.mkdirs();
//            }
//
//            final String fullname = dir + filename;
//            new Timer().schedule(new TimerTask() {
//                @Override
//                public void run() {
//                    new File(fullname).delete();
//                }
//            }, 600000);
//
//            OutputStream os = new FileOutputStream(fullname);
//            workbook.write(os);
//            os.flush();
//            os.close();
//
//            ajaxReturnData.setResult(true);
//            ajaxReturnData.setReturnStr(filename);
//
//        } catch (Exception e) {
//            ajaxReturnData.setResult(false);
//            e.printStackTrace();
//            logger.error(e.getLocalizedMessage());
//        }
//        return ajaxReturnData;
//    }

    /**
     * 用户文件导入
     *
     * @param multipartRequeste
     * @return
     */
    @RequestMapping(value = "health/userFileUpload")
    @ResponseBody
    public String userFileUpload(MultipartHttpServletRequest multipartRequeste, @RequestParam(required = false, defaultValue = "") String orgId){

        try {

            // 文件导入
            Iterator<Map.Entry<String,MultipartFile>> it =  multipartRequeste.getFileMap().entrySet().iterator();

            if (!it.hasNext()) {
                return "没有选择导入文件";
            }

            // 文件上传
            MultipartFile multipartFile = it.next().getValue();
            String extName = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            String tempDir = System.getProperty("user.dir");
            String name = new Date().getTime() + extName.toLowerCase();
            String filName = tempDir.concat(File.separator).concat(name);
            File targetFile = new File(filName);

            try {
                multipartFile.transferTo(targetFile);
            } catch (IOException e) {
                e.printStackTrace();
                return "文件上传失败";
            }

            // 文件内容的读取
            Map<Integer, Map<Integer, String>> mapContent = null;
            try {
                mapContent = ExcelUtil.readExcelContent(targetFile);
            } catch (Exception e) {
                e.printStackTrace();
                return "文件读取失败";
            }

            if (mapContent.size() <= 2) {
                return "文件内没有数据";
            }

            // 文件数据的设定
            //业务单元MAP
            Map<String, Integer> deptMap = new HashMap<String, Integer>();
            // 取得业务单元信息
            HealthDept healthDept = new HealthDept();
            healthDept.setPageSwitch(false);
            List<HealthDept> healthDeptList = healthDeptMapper.selectListByCondition(healthDept);
            for (int i = 0; healthDeptList != null &&i < healthDeptList.size(); i++) {
                Integer deptId = healthDeptList.get(i).getDeptId();
                String deptName = healthDeptList.get(i).getDeptName();
                deptMap.put(deptName, deptId);
            }
            // 错误信息列表
            List<String> errorList = new ArrayList<String>();
            String errMsg = null;
            // 用户数据
            List<HealthUser> healthUserList = new ArrayList<HealthUser>();
            HealthUser healthUser = null;
            // 列编号
            int colIndex = 0;
            String strCell = null;
            // 第一行、第二行为标题
            for (int i = 2; i < mapContent.size(); i++) {
                Map<Integer, String> rowContent = mapContent.get(i);

                // 用户信息的设定
                healthUser = new HealthUser();
                errMsg = "";

                // 序号
                colIndex = 0;
                strCell = rowContent.get(colIndex);
                if (strCell == null || "".equals(strCell.trim()) || "备注".equals(strCell.trim())) {
                    break;
                }
                // 业务单元名称（所属部门）
                colIndex = colIndex + 1;
                strCell = rowContent.get(colIndex);
                if (StringUtils.isBlank(strCell)) {
                    errMsg = errMsg.concat("业务单元名称不能为空、");
                } else {
                    //业务单元信息
                    if (deptMap.containsKey(strCell.trim())) {
                        healthUser.setDeptId(deptMap.get(strCell.trim()));
                        healthUser.setDeptName(strCell.trim());
                    } else {
                        errMsg = errMsg.concat("业务单元名称填写不正确、");
                    }
                }
                // 姓名
                colIndex = colIndex + 1;
                strCell = rowContent.get(colIndex);
                if (StringUtils.isBlank(strCell)) {
                    errMsg = errMsg.concat("姓名不能为空、");
                } else {
                    healthUser.setUserName(strCell.trim());
                }
                // 性别
                colIndex = colIndex + 1;
                strCell = rowContent.get(colIndex);
                if (StringUtils.isBlank(strCell)) {
                    errMsg = errMsg.concat("性别不能为空、");
                } else {
                    // 性别 1:男 2:女
                    if ("男".equals(strCell.trim())) {
                        healthUser.setUserSex("1");
                    } else if ("女".equals(strCell.trim())) {
                        healthUser.setUserSex("2");
                    } else {
                        errMsg = errMsg.concat("性别只能填写男或者女、");
                    }
                }
                // 年龄
                colIndex = colIndex + 1;
                strCell = rowContent.get(colIndex);
                if (StringUtils.isBlank(strCell)) {
                    errMsg = errMsg.concat("年龄不能为空、");
                } else {
                    try {
                        Integer age = Integer.valueOf(strCell.trim());
                        if (age.intValue() < 0 || age.intValue() > 999) {
                            errMsg = errMsg.concat("年龄的范围为0到999、");
                        } else {
                            healthUser.setUserAge(age);
                        }
                    } catch (Exception e) {
                        errMsg = errMsg.concat("年龄只能填写数字、");
                    }
                }
//                // 婚姻状况  1:是 0:否
//                colIndex = colIndex + 1;
//                strCell = rowContent.get(colIndex);
//                if (StringUtils.isBlank(strCell)) {
//                    // 空白的话设成 否
//                    healthUser.setIsMarried("0");
//                } else {
//                    // 婚姻状况 1:是 0:否
//                    if ("是".equals(strCell.trim())) {
//                        healthUser.setIsMarried("1");
//                    } else {
//                        // 空白的话设成 否
//                        healthUser.setIsMarried("0");
//                    }
//                }
                // 手机号
                colIndex = colIndex + 1;
                strCell = rowContent.get(colIndex);
                if (StringUtils.isBlank(strCell)) {
                    errMsg = errMsg.concat("手机号不能为空、");
                } else {
                    String phoneNum = strCell.trim();
                    if(phoneNum.length() != 11){
                        errMsg = errMsg.concat("手机号必须为11位、");
                    }else{
                        Pattern p1 = Pattern.compile("^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\\d|9\\d)\\d{8}$");
                        Matcher m = p1.matcher(phoneNum);
                        if(m.matches()) {
                            healthUser.setMobPhone(phoneNum);
                        } else {
                            errMsg = errMsg.concat("手机号码格式不正确、");
                        }
                    }
                }
                // 身份证号
                colIndex = colIndex + 1;
                strCell = rowContent.get(colIndex);
                if (StringUtils.isBlank(strCell)) {
                    errMsg = errMsg.concat("身份证号不能为空、");
                } else {
                    // 身份证号和年龄、性别的关联CHECK
                    boolean errIdCardFlg = false;
                    String idNun = strCell.trim();
                    String date8 = "";
                    String gender = "1";
                    if ((idNun.length() == 18) || (idNun.length() == 15)) {
                        if (idNun.length() == 18) {
                            date8 = idNun.substring(6,14);
                            if (Integer.valueOf(idNun.substring(16, 17)) % 2 == 0) {
                                gender = "2";
                            }
                        }
                        if (idNun.length() == 15) {
                            date8 = "19" + idNun.substring(6,12);
                            if (Integer.valueOf(idNun.substring(14, 15)) % 2 == 0) {
                                gender = "2";
                            }
                        }

                        String pattern  = "\\d{2,4}\\d{2}\\d{2}";
                        boolean isMatch = Pattern.matches(pattern, date8);
                        if (!isMatch) {
                            errMsg = errMsg.concat("身份证号中日期信息不正确");
                            errIdCardFlg = true;
                        } else {
                            String birYear = date8.substring(0,4);
                            String birMonth = date8.substring(4,6);
                            String birDay = date8.substring(6,8);
                            String birthday = birYear + "-" + birMonth + "-" + birDay;
                            Date birthDay = DateUtil.strToDate(birthday, DateUtil.DEFAULT_DATE_PATTERN);
                            if (birthDay == null) {
                                errMsg = errMsg.concat("身份证号中日期信息不正确");
                                errIdCardFlg = true;
                            } else {
                                Calendar cal = Calendar.getInstance();
                                if (cal.before(birthDay)) {
                                    errMsg = errMsg.concat("身份证号中日期不能比当前日期晚");
                                    errIdCardFlg = true;
                                } else {
                                    int yearNow = cal.get(Calendar.YEAR);
                                    int monthNow = cal.get(Calendar.MONTH);
                                    int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

                                    cal.setTime(birthDay);
                                    int yearBirth = cal.get(Calendar.YEAR);
                                    int monthBirth = cal.get(Calendar.MONTH);
                                    int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
                                    int age = yearNow - yearBirth;
                                    if (monthNow == monthBirth) {
                                        if (dayOfMonthNow < dayOfMonthBirth) {
                                            age--;
                                        }
                                    } else if (monthNow < monthBirth) {
                                        age--;
                                    } else{
                                        //  age
                                    }

                                    if (healthUser.getUserAge().intValue() != age) {
                                        errMsg = errMsg.concat("年龄和身份证号的填写不一致");
                                        errIdCardFlg = true;
                                    }
                                }
                            }
                        }

                        if (!healthUser.getUserSex().equals(gender)) {
                            errMsg = errMsg.concat("性别和身份证号的填写不一致");
                            errIdCardFlg = true;
                        }

                        if (!errIdCardFlg) {
                            healthUser.setCardId(strCell.trim());
                        }
                    } else {
                        if (idNun.length() != 8 && idNun.length() != 9){
                            errMsg = errMsg.concat("身份证以外的证件号码长度必须是8位或9位");
                        }else{
                            healthUser.setCardId(strCell.trim());
                        }
                    }
                }
//                // 套餐升级  1:是 0:否
//                colIndex = colIndex + 1;
//                strCell = rowContent.get(colIndex);
//                if (StringUtils.isBlank(strCell)) {
//                    // 空白的话设成 否
//                    healthUser.setPkgUpgrade("0");
//                } else {
//                    // 套餐升级 1:是 0:否
//                    if ("是".equals(strCell.trim())) {
//                        healthUser.setPkgUpgrade("1");
//                    } else {
//                        // 空白的话设成 否
//                        healthUser.setPkgUpgrade("0");
//                    }
//                }
                // 套餐类型 B1(男性)、B2(女性)、C1(＜40岁男性)、C2(＜40岁女性)、C3(≥40岁男性)、C4(≥40岁女性)、D1(＜40岁男性)、D2(＜40岁女性)、D3(≥40岁男性)、D4(≥40岁女性)
                colIndex = colIndex + 1;
                strCell = rowContent.get(colIndex);
                if (StringUtils.isBlank(strCell.trim())) {
                    errMsg = errMsg.concat("套餐类型不能为空、");
                } else {
                    boolean err = false;
                    if (strCell.trim().equals("B1")) {
                        if (healthUser.getUserSex().equals("2")) {
                            errMsg = errMsg.concat("套餐类型与性别不符、");
                            err = true;
                        }
                    } else if (strCell.trim().equals("B2")) {
                        if (healthUser.getUserSex().equals("1")) {
                            errMsg = errMsg.concat("套餐类型与性别不符、");
                            err = true;
                        }
                    } else if (strCell.trim().equals("C1")) {
                        if (healthUser.getUserSex().equals("2")) {
                            errMsg = errMsg.concat("套餐类型与性别不符、");
                            err = true;
                        }
                        if (healthUser.getUserAge() >= 40) {
                            errMsg = errMsg.concat("套餐类型与年龄不符、");
                            err = true;
                        }
                    } else if (strCell.trim().equals("C2")) {
                        if (healthUser.getUserSex().equals("1")) {
                            errMsg = errMsg.concat("套餐类型与性别不符、");
                            err = true;
                        }
                        if (healthUser.getUserAge() >= 40) {
                            errMsg = errMsg.concat("套餐类型与年龄不符、");
                            err = true;
                        }
                    } else if (strCell.trim().equals("C3")) {
                        if (healthUser.getUserSex().equals("2")) {
                            errMsg = errMsg.concat("套餐类型与性别不符、");
                            err = true;
                        }
                        if (healthUser.getUserAge() < 40) {
                            errMsg = errMsg.concat("套餐类型与年龄不符、");
                            err = true;
                        }
                    } else if (strCell.trim().equals("C4")) {
                        if (healthUser.getUserSex().equals("1")) {
                            errMsg = errMsg.concat("套餐类型与性别不符、");
                            err = true;
                        }
                        if (healthUser.getUserAge() < 40) {
                            errMsg = errMsg.concat("套餐类型与年龄不符、");
                            err = true;
                        }
                    } else if (strCell.trim().equals("D1")) {
                        if (healthUser.getUserSex().equals("2")) {
                            errMsg = errMsg.concat("套餐类型与性别不符、");
                            err = true;
                        }
                        if (healthUser.getUserAge() >= 40) {
                            errMsg = errMsg.concat("套餐类型与年龄不符、");
                            err = true;
                        }
                    } else if (strCell.trim().equals("D2")) {
                        if (healthUser.getUserSex().equals("1")) {
                            errMsg = errMsg.concat("套餐类型与性别不符、");
                            err = true;
                        }
                        if (healthUser.getUserAge() >= 40) {
                            errMsg = errMsg.concat("套餐类型与年龄不符、");
                            err = true;
                        }
                    } else if (strCell.trim().equals("D3")) {
                        if (healthUser.getUserSex().equals("2")) {
                            errMsg = errMsg.concat("套餐类型与性别不符、");
                            err = true;
                        }
                        if (healthUser.getUserAge() < 40) {
                            errMsg = errMsg.concat("套餐类型与年龄不符、");
                            err = true;
                        }
                    } else if (strCell.trim().equals("D4")) {
                        if (healthUser.getUserSex().equals("1")) {
                            errMsg = errMsg.concat("套餐类型与性别不符、");
                            err = true;
                        }
                        if (healthUser.getUserAge() < 40) {
                            errMsg = errMsg.concat("套餐类型与年龄不符、");
                            err = true;
                        }
                    } else {
                        errMsg = errMsg.concat("套餐类型不合法、");
                        err = true;
                    }
                    if (!err) {
                        healthUser.setPkgType(strCell.trim());
                    }
                }

                //如果套餐类型为C1、C2、C3、C4,则需填写"2023年是否已做或已保留无痛胃肠镜项目"
                String pkg_type = StringUtils.defaultString(healthUser.getPkgType(), "");
                colIndex = colIndex + 1;
                strCell = rowContent.get(colIndex);
                if (pkg_type.equals("C1") || pkg_type.equals("C2") || pkg_type.equals("C3") || pkg_type.equals("C4")) {
                    if (StringUtils.isBlank(strCell.trim())) {
                        errMsg = errMsg.concat("C级人员需要填写2023年是否已做或已保留无痛胃肠镜项目、");
                    }

                    if (!strCell.trim().equals("是") && !strCell.trim().equals("否")) {
                        errMsg = errMsg.concat("C级人员需要填写\"是/否\"、");
                    }
                    healthUser.setHaveDoneOptionalOption(strCell.trim());
                }

                // 体检状态（默认值为1）
                healthUser.setState("1");
                // 修改次数（默认值为0）
                healthUser.setModifyNum(0);

                // 重复check判断用
                healthUserList.add(healthUser);

                // 错误信息有无的判断
                if (!"".equals(errMsg.trim())) {
                    errMsg = errMsg.substring(0, errMsg.length()-1);
                    errMsg = "第" + (i-1) + "条数据的错误信息：" + errMsg;
                    errorList.add(errMsg);
                    continue;
                }
            }

            // 临时文件的删除
            final String fullname = filName;
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    new File(fullname).delete();
                }
            }, 10000);

            // 数据文件内重复数据的判断
            HealthUser healthUser1 = null;
            HealthUser healthUser2 = null;
            for (int i = 0; i<healthUserList.size(); i++) {
                healthUser1 = healthUserList.get(i);
                for (int j = i+1; j<healthUserList.size(); j++) {
                    healthUser2 = healthUserList.get(j);
                    errMsg = "";
                    if (StringUtils.isNotEmpty(healthUser1.getMobPhone()) && StringUtils.isNotEmpty(healthUser2.getMobPhone())) {
                        if (healthUser1.getMobPhone().equals(healthUser2.getMobPhone())) {
                            errMsg = errMsg + "手机号相同、";
                        }
                    }
                    if (StringUtils.isNotEmpty(healthUser1.getCardId()) && StringUtils.isNotEmpty(healthUser2.getCardId())) {
                        if (healthUser1.getCardId().equals(healthUser2.getCardId())) {
                            errMsg = errMsg + "身份证号相同、";
                        }
                    }

                    if (!"".equals(errMsg.trim())) {
                        errMsg = errMsg.substring(0, errMsg.length()-1);
                        errMsg = "第" + (i+1) + "条数据和第" + (j+1) + "条数据的" + errMsg;
                        errorList.add(errMsg);
                    }
                }
            }

            // 有错误信息时
            if (errorList.size() > 0) {
                String jsonStr = "ERROR_LIST:" + JSON.toJSONString(errorList);
                return jsonStr;
            }

            // 没有用户数据时
            if (healthUserList.size() == 0) {
                return "文件内没有用户数据";
            }

            // 数据导入
            AjaxReturnData ajaxReturnData = healthUserService.addHealthUserList(healthUserList);

            // ajaxReturnData.Result = false --->> 数据库内有身份证号、手机号、姓名相同的数据
            // ajaxReturnData.Result = true --->> 导入成功
            return ajaxReturnData.getMessage();
        }  catch (Exception e) {
            e.printStackTrace();
            logger.error("异常信息:", e.getMessage());
            logger.error(e.getLocalizedMessage());
            return "数据导入失败，请联系相关人员确认";
        }
    }

    /**
     *  体检人员添加
     *
     * @return
     */
    @RequestMapping("health/toAddUser")
    public ModelAndView userAdd() {
        ModelAndView modelAndView = new ModelAndView("operation/health/userAdd");
//        // 可选择体检机构的取得
//        HealthOrg healthOrg = new HealthOrg();
//        healthOrg.setPageSwitch(false);
//        List<HealthOrg> healthOrgList = healthOrgMapper.selectListByCondition(healthOrg);
//
//        // 添加用户时，页面升级套餐默认为“否”，只有升级套餐的才可以选择305医院
//        for(HealthOrg healthOrg1:healthOrgList){
//            if("解放军三〇五医院".equals(healthOrg1.getOrgName())){
//                healthOrgList.remove(healthOrg1);
//                break;
//            }
//        }
//
//        modelAndView.addObject("orgList", healthOrgList);
        // 可选择业务单元的取得
        HealthDept healthDept = new HealthDept();
        healthDept.setPageSwitch(false);
        List<HealthDept> healthDeptList = healthDeptMapper.selectListByCondition(healthDept);
        modelAndView.addObject("deptList", healthDeptList);
//        //体检周期查询
//        HealthCycle healthCycle = new HealthCycle();
//        healthCycle.setPageSwitch(false);
//        healthCycle.setCycleState("1");
//        List<HealthCycle> healthCycleList = healthCycleMapper.selectListByCondition(healthCycle);
//        if (healthCycleList != null && healthCycleList.size() > 0) {
//            //体检周期的开始日期
//            String cycleStartDateStr = healthCycleList.get(0).getStartDateStr();
//            modelAndView.addObject("cycleStartDateStr", cycleStartDateStr);
//            //体检周期的结束日期
//            String cycleEndDateStr = healthCycleList.get(0).getEndDateStr();
//            modelAndView.addObject("cycleEndDateStr", cycleEndDateStr);
//        }
//        // 体检套餐的选择
//        HealthPackage healthPackage = new HealthPackage();
//        healthPackage.setPageSwitch(false);
//        healthPackage.setPkgState("1");
//        List<HealthPackage> healthPackageList = healthPackageMapper.selectListByCondition(healthPackage);
//        modelAndView.addObject("pgkList", healthPackageList);
//        // 默认套餐类型
//        if (healthPackageList != null && healthPackageList.size() > 0) {
//            HealthPackage defaultPkg = healthPackageList.get(0);
//            // 有多个套餐时，至少有一个默认套餐
//            if (healthPackageList.size() > 1) {
//                int defaultCount = 0;
//                for (HealthPackage healthPackage1: healthPackageList) {
//                    if ("1".equals(healthPackage1.getIsDefault())) {
//                        defaultPkg = healthPackage1;
//                        defaultCount++;
//                    }
//                }
//
//                if (defaultCount != 1) {
//                    modelAndView = new ModelAndView("msg");
//                    modelAndView.addObject("msg", "体检套餐的设定不正确，有多个套餐时需要设定一个默认套餐,请重新设定");
//                    //返回到套餐页面
//                    modelAndView.addObject("returnUrl", "operation/health/pkgList");
//                    return modelAndView;
//                }
//            }
//
//            modelAndView.addObject("defaultPkgId", defaultPkg.getPkgId());
//            modelAndView.addObject("defaultPkgLineAge", defaultPkg.getPkgLineAge());
//        } else {
//            // 没有 设定体检套餐时
//            modelAndView.addObject("defaultPkgId", "");
//            modelAndView.addObject("defaultPkgLineAge", 40);
//        }

        return modelAndView;
    }
    @RequestMapping(value = "health/userDoAdd")
    public ModelAndView doAddUser(HealthUser healthUser, HealthUserAppointment vmHuaInfo) {
        ModelAndView modelAndView = new ModelAndView("msg");
        if ("是".equals(vmHuaInfo.getNeedOptionalOption())) {
            vmHuaInfo.setOptionalOption("无痛胃肠镜");
        }

        // 判断套餐类型是否会因为在体检日期当天用户的年龄达到了40岁而发生变化
        if ("2".equals(healthUser.getState()) && healthUser.getUserAge() == 39 && StringUtils.isNotBlank(vmHuaInfo.getCheckDateStr())) {
            if (healthUser.getPkgType().startsWith("C") || healthUser.getPkgType().startsWith("D")) {
                // 计算体检日期当天，用户的年龄
                Date checkDate = DateUtil.strToDate(vmHuaInfo.getCheckDateStr(), DateUtil.DEFAULT_DATE_PATTERN);
                int age = CalculateUserAgeUtils.calculate(healthUser.getCardId(), checkDate);
                if (age == 40) {
                    ModelAndView view = new ModelAndView("msg");
                    view.addObject("msg", "发现预约日期跨越40岁 提前预约日期会产生套餐变更 请联系管理员");
                    view.addObject("returnUrl", "operation/health/userList");
                    return view;
                }
            }
        }

        // 判断选择的机构在选择的体检日期内是否有安排体检
        if ("2".equals(healthUser.getState()) && vmHuaInfo.getOrgId() != null) {
            HealthOrgAppointment hoAppointment = new HealthOrgAppointment();
            hoAppointment.setOrgId(vmHuaInfo.getOrgId());
            hoAppointment.setAppointmentDate(DateUtil.toUnixTimeStampByDate(vmHuaInfo.getCheckDateStr()));
            //查询结果
            List<HealthOrgAppointment> hoaInfoList = healthOrgAppointmentMapper.selectListByCondition(hoAppointment);
            if (hoaInfoList == null || hoaInfoList.size() == 0) {
                ModelAndView view = new ModelAndView("msg");
                view.addObject("msg", "您选择的体检机构在您选择的体检时间内未安排体检，请重新选择");
                view.addObject("returnUrl", "operation/health/userList");
                return view;
            } else {
                HealthOrgAppointment healthOrgAppointment = hoaInfoList.get(0);
                if (healthOrgAppointment.getAppointmenterNum() == 0) {
                    ModelAndView view = new ModelAndView("msg");
                    view.addObject("msg", "您选择的体检机构在您选择的体检时间内未安排体检，请重新选择");
                    view.addObject("returnUrl", "operation/health/userList");
                    return view;
                }
            }
        }

        boolean insertResult = healthUserService.insertUserAndUserAppointment(healthUser, vmHuaInfo);
        if (insertResult) {
            modelAndView.addObject("msg", "体检人员新增成功");
        } else {
            modelAndView.addObject("msg", "体检人员新增失败");
        }
        modelAndView.addObject("returnUrl", "operation/health/userList");
        return modelAndView;
    }

    /**
     * 根据业务单元、套餐是否升级、套餐类型设置体检机构选项
     *
     * @param deptId
     * @param pkgUpgrade
     * @param pkgType
     * @return
     */
    @RequestMapping("health/getOrgOption")
    @ResponseBody
    public AjaxReturnEntity getOrgOption(String deptId, String pkgUpgrade, String pkgType, String haveDoneOptionalOption, String needOptionalOption) {

        AjaxReturnEntity ajaxReturnEntity = new AjaxReturnEntity();

        // 可选择体检机构的取得
        HealthOrg healthOrg = new HealthOrg();
        healthOrg.setPageSwitch(false);
        healthOrg.setOrgState(true);

//        // 体检升级套餐选择时.取得该业务单元设定的的体检机构
//        if (!StringUtils.isBlank(pkgUpgrade)) {
//            if ("1".equals(pkgUpgrade)) {
//                healthOrg.setPkgUpgradeFlg(true);
//            } else {
//                // 选择 否时，检索全部体检机构
//                // healthOrg.setPkgUpgradeFlg(false);
//            }
//        }

        List<HealthOrg> healthOrgList = healthOrgMapper.selectListByCondition(healthOrg);
        if (healthOrgList == null || healthOrgList.size() == 0) {
            ajaxReturnEntity.setResult(false);
            ajaxReturnEntity.setMessage("没有满足条件的可选择体检机构");
            return ajaxReturnEntity;
        }

        // 业务单元选择时.取得该业务单元设定的的体检机构
        List<HealthOrg> retHealthOrgList = new ArrayList<HealthOrg>();
        String[] orgIdArray = null;
        if (!StringUtils.isBlank(deptId)) {
            HealthDept healthDeptment = healthDeptMapper.selectByPrimaryKey(Integer.valueOf(deptId));
            String orgIds = healthDeptment.getOrgIds();
            if (!StringUtils.isBlank(orgIds)) {
                orgIdArray = orgIds.split(",");

                // 取得该业务单元设定的的体检机构
                for (HealthOrg healthOrg1: healthOrgList) {
                    for (String orgId: orgIdArray) {
                        if (healthOrg1.getOrgId().intValue() == Integer.valueOf(orgId).intValue()) {
                            retHealthOrgList.add(healthOrg1);
                            break;
                        }
                    }
                }

                if(retHealthOrgList == null || retHealthOrgList.size() == 0) {
                    ajaxReturnEntity.setResult(false);
                    ajaxReturnEntity.setMessage("没有满足条件的可选择体检机构");
                    return ajaxReturnEntity;
                }
            } else {
                // 没有设定时，全部体检机构都可以使用
            }
        }

        // 套餐类型时，根据套餐类型过滤体检机构
        List<HealthOrg> retretHealthOrgList = new ArrayList<HealthOrg>();
        if (!StringUtils.isBlank(pkgType)) {
            List<HealthOrg> initOrgList = retHealthOrgList.size() > 0 ? retHealthOrgList : healthOrgList;
            //B1、B2套餐类型的体检机构是: 北京电力医院(含无痛胃肠镜)、北京电力医院(不含无痛胃肠镜)、北京航天中心医院(含无痛胃肠镜)、北京航天中心医院(不含无痛胃肠镜)、福临门大厦上门体检
            //C1、C2、C3、C4套餐类型、并且2023年已做或已保留无痛胃肠镜项目的体检机构是: 美兆东方广场分院、美兆润美分院、爱康双子座君安分院、爱康大望路分院、爱康光华路SOHO分院、北京电力医院(不含无痛胃肠镜)、北京航天中心医院(不含无痛胃肠镜)、福临门大厦上门体检
            //C1、C2、C3、C4套餐类型、并且2023年未做且未保留无痛胃肠镜项目、但后续安排无痛胃肠镜的体检机构是: 美兆东方广场分院、美兆润美分院、北京电力医院(含无痛胃肠镜)、北京航天中心医院(含无痛胃肠镜)、福临门大厦上门体检
            //C1、C2、C3、C4套餐类型、并且2023年未做且未保留无痛胃肠镜项目、后续不安排无痛胃肠镜的体检机构是:美兆东方广场分院、美兆润美分院、爱康双子座君安分院、爱康大望路分院、爱康光华路SOHO分院、北京电力医院(不含无痛胃肠镜)、北京航天中心医院(不含无痛胃肠镜)、福临门大厦上门体检
            //D1、D2、D3、D4套餐类型、但后续安排无痛胃肠镜的体检机构是: 北京电力医院D、北京航天中心医院(西三环)、福临门大厦上门体检、北京航天中心医院(玉泉路D)
            //D1、D2、D3、D4套餐类型、后续不安排无痛胃肠镜的体检机构是:美兆东方广场分院、美兆润美分院、爱康双子座君安分院、爱康大望路分院、爱康光华路SOHO分院、北京中医医院、北京电力医院D、北京航天中心医院(西三环)、福临门大厦上门体检、北京航天中心医院(玉泉路D)
            if (pkgType.equals("B1") || pkgType.equals("B2")) {
                List<String> orgNameList = null;
                if ("是".equals(needOptionalOption)) {
                    orgNameList = Arrays.asList("北京电力医院(含无痛胃肠镜)", "北京航天中心医院(含无痛胃肠镜)", "福临门大厦上门体检");
                } else {
                    orgNameList = Arrays.asList("北京电力医院(不含无痛胃肠镜)", "北京航天中心医院(不含无痛胃肠镜)", "福临门大厦上门体检");
                }
                for (HealthOrg healthOrg1 : initOrgList) {
                    for (String healthOrgName : orgNameList) {
                        if (healthOrg1.getOrgName().equals(healthOrgName)) {
                            retretHealthOrgList.add(healthOrg1);
                            break;
                        }
                    }
                }
            } else if (pkgType.equals("C1") || pkgType.equals("C2") || pkgType.equals("C3") || pkgType.equals("C4")) {
                List<String> orgNameList = null;
                if ("是".equals(haveDoneOptionalOption)) {
                    orgNameList = Arrays.asList("美兆东方广场分院", "美兆润美分院", "爱康双子座君安分院", "爱康大望路分院", "爱康光华路SOHO分院", "北京电力医院(不含无痛胃肠镜)", "北京航天中心医院(不含无痛胃肠镜)", "福临门大厦上门体检");
                } else {
                    if ("是".equals(needOptionalOption)) {
                        orgNameList = Arrays.asList("美兆东方广场分院", "美兆润美分院", "北京电力医院(含无痛胃肠镜)", "北京航天中心医院(含无痛胃肠镜)", "福临门大厦上门体检");
                    } else {
                        orgNameList = Arrays.asList("美兆东方广场分院", "美兆润美分院", "爱康双子座君安分院", "爱康大望路分院", "爱康光华路SOHO分院", "北京电力医院(不含无痛胃肠镜)", "北京航天中心医院(不含无痛胃肠镜)", "福临门大厦上门体检");
                    }
                }
                for (HealthOrg healthOrg1 : initOrgList) {
                    for (String healthOrgName : orgNameList) {
                        if (healthOrg1.getOrgName().equals(healthOrgName)) {
                            retretHealthOrgList.add(healthOrg1);
                            break;
                        }
                    }
                }
            } else if (pkgType.equals("D1") || pkgType.equals("D2") || pkgType.equals("D3") || pkgType.equals("D4")) {
                List<String> list = null;
                if ("是".equals(needOptionalOption)) {
                    list = Arrays.asList("北京电力医院D", "北京航天中心医院(西三环)", "福临门大厦上门体检", "北京航天中心医院(玉泉路D)");
                } else {
                    list = Arrays.asList("美兆东方广场分院", "美兆润美分院", "爱康双子座君安分院", "爱康大望路分院", "爱康光华路SOHO分院", "北京中医医院", "北京电力医院D", "北京航天中心医院(西三环)", "福临门大厦上门体检", "北京航天中心医院(玉泉路D)");
                }
                for (HealthOrg healthOrg1 : initOrgList) {
                    for (String healthOrgName : list) {
                        if (healthOrg1.getOrgName().equals(healthOrgName)) {
                            retretHealthOrgList.add(healthOrg1);
                            break;
                        }
                    }
                }
            }

            if(retretHealthOrgList == null || retretHealthOrgList.size() == 0) {
                ajaxReturnEntity.setResult(false);
                ajaxReturnEntity.setMessage("没有满足条件的可选择体检机构");
                return ajaxReturnEntity;
            }
        }

//        // 只有升级套餐的才可以选择305医院
//        for(HealthOrg healthOrg1:retHealthOrgList){
//            if("0".equals(pkgUpgrade) && "解放军三〇五医院".equals(healthOrg1.getOrgName())){
//                retHealthOrgList.remove(healthOrg1);
//                break;
//            }
//        }
//        for(HealthOrg healthOrg2:healthOrgList){
//            if("0".equals(pkgUpgrade) && "解放军三〇五医院".equals(healthOrg2.getOrgName())){
//                healthOrgList.remove(healthOrg2);
//                break;
//            }
//        }

        if (retretHealthOrgList != null && retretHealthOrgList.size() > 0) {// 经过套餐类型过滤的数据
            ajaxReturnEntity.setResult(true);
            ajaxReturnEntity.setList(retretHealthOrgList);
        } else if(retHealthOrgList != null && retHealthOrgList.size() > 0) {// 经过业务单元过滤的数据
            ajaxReturnEntity.setResult(true);
            ajaxReturnEntity.setList(retHealthOrgList);
        } else {
            ajaxReturnEntity.setResult(true);
            ajaxReturnEntity.setList(healthOrgList);
        }

        return ajaxReturnEntity;
    }

    /**
     * 根据性别和年龄，查询套餐类型
     *
     * @param userSex 1:男 2:女
     * @param userAge
     * @return
     */
    @RequestMapping("health/getPkgTypeOption")
    @ResponseBody
    public AjaxReturnEntity getPkgTypeOption(String userSex, String userAge) {
        AjaxReturnEntity ajaxReturnEntity = new AjaxReturnEntity();

        if (StringUtils.isBlank(userSex) || StringUtils.isBlank(userAge)) {
            ajaxReturnEntity.setResult(false);
            ajaxReturnEntity.setMessage("性别和年龄不能为空");
            return ajaxReturnEntity;
        }
        if (Integer.valueOf(userAge) < 0 || Integer.valueOf(userAge) > 999) {
            ajaxReturnEntity.setResult(false);
            ajaxReturnEntity.setMessage("年龄的范围为0到999");
            return ajaxReturnEntity;
        }

        //B1(男性)、B2(女性)、C1(＜40岁男性)、C2(＜40岁女性)、C3(≥40岁男性)、C4(≥40岁女性)、D1(＜40岁男性)、D2(＜40岁女性)、D3(≥40岁男性)、D4(≥40岁女性)
        List<String> pkgTypeList = new ArrayList<String>();
        if ("1".equals(userSex)) {
            pkgTypeList.add("B1");
            if (Integer.valueOf(userAge) < 40) {
                pkgTypeList.add("C1");
                pkgTypeList.add("D1");
            } else {
                pkgTypeList.add("C3");
                pkgTypeList.add("D3");
            }
        } else if ("2".equals(userSex)) {
            pkgTypeList.add("B2");
            if (Integer.valueOf(userAge) < 40) {
                pkgTypeList.add("C2");
                pkgTypeList.add("D2");
            } else {
                pkgTypeList.add("C4");
                pkgTypeList.add("D4");
            }
        }

        ajaxReturnEntity.setResult(true);
        ajaxReturnEntity.setList(pkgTypeList);
        return ajaxReturnEntity;
    }

//    /**
//     * 根据选择的体检机构 设定体检套餐
//     *
//     * @param orgId
//     * @return
//     */
//    @RequestMapping("health/getPkgOption")
//    @ResponseBody
//    public AjaxReturnEntity getPkgOption(String orgId) {
//
//        AjaxReturnEntity ajaxReturnEntity = new AjaxReturnEntity();
//
//        // 体检机构对应的体检套餐的取得
//        HealthOrg healthOrg = healthOrgMapper.selectByPrimaryKey(Integer.valueOf(orgId));
//        if (healthOrg == null || StringUtils.isBlank(healthOrg.getPkgIds())) {
//            ajaxReturnEntity.setResult(false);
//            ajaxReturnEntity.setMessage("没有满足条件的可选择体检套餐");
//            return ajaxReturnEntity;
//        }
//
//        List<HealthPackage> pkgList = new ArrayList<HealthPackage>();
//        String pkgIds = healthOrg.getPkgIds();
//        if (!StringUtils.isBlank(pkgIds)) {
//            String[] pkgIdArray = pkgIds.split(",");
//            for (String pkgId: pkgIdArray) {
//                HealthPackage healthPackage = healthPackageMapper.selectByPrimaryKey(Integer.valueOf(pkgId));
//                if ("1".equals(healthPackage.getPkgState())) {
//                    pkgList.add(healthPackage);
//                }
//            }
//        }
//
//        if (pkgList.size() == 0) {
//            ajaxReturnEntity.setResult(false);
//            ajaxReturnEntity.setMessage("没有满足条件的可选择体检套餐");
//        } else {
//            ajaxReturnEntity.setResult(true);
//            ajaxReturnEntity.setList(pkgList);
//        }
//
//        return ajaxReturnEntity;
//    }

    /**
     *  体检人员重名CHECK
     *
     * @param healthUser
     * @return
     */
    @RequestMapping("health/checkUserInfo")
    @ResponseBody
    public Boolean checkUserInfo(HealthUser healthUser) {
        List<HealthUser> userList = healthUserMapper.checkUserInfoByCondition(healthUser);
        if (userList.size() == 0) {
            return true;
        }

        // 添加时
        if (healthUser.getUserId() == null) {
            // 件数大于0时， 标识数据库内有重复数据  return false;
        } else {
            // 修改时
            if (userList.size() == 1) {
                // 修改的当前记录的数据时
                if (userList.get(0).getUserId().intValue() == healthUser.getUserId().intValue()) {
                    return true;
                }
            } else {
                // 件数大于1时， 标识数据库内有重复数据  return false;
            }
        }
        // 添加时 或  修改的其他记录的数据时
        return false;
    }

    /**
     *  体检信息CHECK
     * @param healthUser
     * @param vmHuaInfo
     * @return
     */
    @RequestMapping("health/checkAppointmentInfo")
    @ResponseBody
    public AjaxReturnData checkAppointmentInfo(HttpServletRequest request, HealthUser healthUser, HealthUserAppointment vmHuaInfo) {

        AjaxReturnData ajaxReturnData = new AjaxReturnData();

        //取得用户信息修改前的数据
        HealthUser oldHealthUser = healthUserMapper.selectByPrimaryKey(healthUser.getUserId());
        HealthUserAppointment oldHuaInfo = healthUserAppointmentMapper.selectByPrimaryKey(vmHuaInfo.getUaId());

        // 未预约的情况下，进行的CHECK
        if ("1".equals(healthUser.getState())) {
            // 新增用户时checkDateStr、orgId都为空，该方法不执行，因此以下判断可以不要
            if (oldHealthUser == null) {
                ajaxReturnData.setResult(true);
                ajaxReturnData.setMessage("未预约的情况下，不需要CHECK");
                return ajaxReturnData;
            } else {
                // 更新前的状态必须是未预约、取消预约
                if("1".equals(oldHealthUser.getState()) || "3".equals(oldHealthUser.getState())) {
                    ajaxReturnData.setResult(true);
                    ajaxReturnData.setMessage("未预约的情况下，不需要CHECK");
                    return ajaxReturnData;
                } else {
                    ajaxReturnData.setResult(false);
                    ajaxReturnData.setMessage("只有已取消预约或未预约的情况下，才可将状态设定为未预约！");
                    return ajaxReturnData;
                }
            }
        }
        //取消预约的情况下，进行的CHECK
        if ("3".equals(healthUser.getState())) {
            // 体检机构取消时间CHECK
            if (oldHuaInfo.getCancelTime() != null) {
                ajaxReturnData.setResult(false);
                ajaxReturnData.setMessage("您的预约已取消，不需要再次取消！");
                return ajaxReturnData;
            } else {
                HealthOrgAppointment appointment = new HealthOrgAppointment();
                appointment.setOrgId(oldHuaInfo.getOrgId());
                appointment.setAppointmentDate(oldHuaInfo.getCheckDate());
                List<HealthOrgAppointment> appointmentList = healthOrgAppointmentMapper.selectListByCondition(appointment);
                if (appointmentList == null || appointmentList.size() == 0) {
                    ajaxReturnData.setResult(false);
                    ajaxReturnData.setMessage("您已预约的体检机构的数据不正确，请联系管理员");
                    return ajaxReturnData;
                }
                if (appointmentList.size() > 1) {
                    ajaxReturnData.setResult(false);
                    ajaxReturnData.setMessage("您已预约的体检机构的数据不正确，请联系管理员");
                    return ajaxReturnData;
                }
                // 只有在当前用户不是管理员的情况下，才校验取消时间
                MemberBase memberBase = (MemberBase)request.getSession().getAttribute("memInfo");
                if (memberBase != null && memberBase.getHealthDeptId() != null ) {
                    HealthOrgAppointment orgAppointment = appointmentList.get(0);
                    if(DateUtil.toIntDate(oldHuaInfo.getCheckDate()).after(new Date()) && DateUtil.toIntDate(orgAppointment.getCancelTime()).before(new Date())) {
                        String cancelTime = orgAppointment.getCancelTimeStr();
                        ajaxReturnData.setResult(false);
                        ajaxReturnData.setMessage("您的取消时间必须在【"+ cancelTime +"】之前。如果要取消，请联系管理员");
                        return ajaxReturnData;
                    }
                }
                // 只能取消当前周期的预约
                HealthCycle healthCycle = new HealthCycle();
                healthCycle.setPageSwitch(false);
                healthCycle.setCycleState("1");
                List<HealthCycle> healthCycleList = healthCycleMapper.selectListByCondition(healthCycle);
                if (healthCycleList != null && healthCycleList.size() > 0) {
                    for (HealthCycle healthCycleDB : healthCycleList) {
                        if (oldHuaInfo.getCheckDateStr().compareTo(healthCycleDB.getStartDateStr()) >= 0
                                && oldHuaInfo.getCheckDateStr().compareTo(healthCycleDB.getEndDateStr()) <= 0) {
                            // 在预约周期内
                        } else  {
                            ajaxReturnData.setResult(false);
                            ajaxReturnData.setMessage("您只能取消当前周期时间内的已预约体检日期！预约周期："
                                    + healthCycleDB.getStartDateStr() + " ~ " + healthCycleDB.getEndDateStr());
                            return ajaxReturnData;
                        }
                    }
                }
            }
            ajaxReturnData.setResult(true);
            ajaxReturnData.setMessage("取消预约不需要其他CHECK");
            return ajaxReturnData;
        } else {
            // 预约情况下 (修改前后的状态都是 2：已预约)
            if ("2".equals(healthUser.getState()) &&
                    oldHealthUser != null && "2".equals(oldHealthUser.getState()) &&
                    oldHuaInfo != null) {
                //预约信息没有变化的情况下，不进行CHECK
                if (healthUser.getState().equals(oldHealthUser.getState())
                        && healthUser.getPkgType().equals(oldHealthUser.getPkgType())
                        && vmHuaInfo.getOrgId().intValue() == oldHuaInfo.getOrgId().intValue()
                        && vmHuaInfo.getCheckDateStr().equals(oldHuaInfo.getCheckDateStr())) {
                    // 还需要进行预约周期、预约机构人数等的CHECK
                    //ajaxReturnData.setResult(true);
                    //ajaxReturnData.setMessage("没有修改预约信息不需要CHECK");
                    //return ajaxReturnData;
                } else {
                    // 所有预约入口在修改预约时都改为先取消原来的预约后，再进行新的预约来实现修改预约
                    ajaxReturnData.setResult(false);
                    ajaxReturnData.setMessage("请先取消原来的预约后才能重新预约！");
                    return ajaxReturnData;
                }
            }
        }

        // 是否在预约周期之内
        HealthCycle healthCycle = new HealthCycle();
        healthCycle.setPageSwitch(false);
        healthCycle.setCycleState("1");
        List<HealthCycle> healthCycleList = healthCycleMapper.selectListByCondition(healthCycle);
        if (healthCycleList != null && healthCycleList.size() > 0) {
            for (HealthCycle healthCycleDB : healthCycleList) {
                if (vmHuaInfo.getCheckDateStr().compareTo(healthCycleDB.getStartDateStr()) >= 0
                        && vmHuaInfo.getCheckDateStr().compareTo(healthCycleDB.getEndDateStr()) <= 0) {
                    // 在预约周期内
                } else  {
                    ajaxReturnData.setResult(false);
                    ajaxReturnData.setMessage("您预约的体检日期必须在当前可预约周期时间内！预约周期："
                            + healthCycleDB.getStartDateStr() + " ~ " + healthCycleDB.getEndDateStr());
                    return ajaxReturnData;
                }
            }
        } else {
            ajaxReturnData.setResult(false);
            ajaxReturnData.setMessage("还没有安排体检周期，不能进行预约");
            return ajaxReturnData;
        }

        // 预约机构人数CHECK
        Integer appointmentNum = 0;
        // 预约机构满额人数的取得
        HealthOrgAppointment orgAppointment = new HealthOrgAppointment();
        orgAppointment.setOrgId(vmHuaInfo.getOrgId());
        orgAppointment.setAppointmentDate(DateUtil.toUnixTimeStampByDate(vmHuaInfo.getCheckDateStr()));
        List<HealthOrgAppointment> orgAppointmentList = healthOrgAppointmentMapper.selectListByCondition(orgAppointment);
        if (orgAppointmentList != null && orgAppointmentList.size() == 1) {
            // 只取一条
            orgAppointment = orgAppointmentList.get(0);
            appointmentNum = orgAppointment.getAppointmenterNum();
            if (appointmentNum == 0) {
                ajaxReturnData.setResult(false);
                ajaxReturnData.setMessage("您选择的机构的当天没有预约名额，请选择其它体检机构或其它日期进行预约！");
                return ajaxReturnData;
            }
        } else {
            ajaxReturnData.setResult(false);
            ajaxReturnData.setMessage("您预约的体检机构的数据不正确，请联系管理员");
            return ajaxReturnData;
        }

        // 该机构已经预约了的人数的取得
        HealthUserAppointment userAppointment = new HealthUserAppointment();
        userAppointment.setPageSwitch(false);
        userAppointment.setOrgId(vmHuaInfo.getOrgId());
        userAppointment.setCheckDate(DateUtil.toUnixTimeStampByDate(vmHuaInfo.getCheckDateStr()));
        userAppointment.setAppointmentedFlg("1");// 已预约的
        List<HealthUserAppointment> userAppointmentList = healthUserAppointmentMapper.selectListByCondition(userAppointment);
        Integer appointmentNumUser = 0;
        if (userAppointmentList != null) {
            appointmentNumUser = userAppointmentList.size();
        }

        if (appointmentNum <= appointmentNumUser) {
            ajaxReturnData.setResult(false);
            ajaxReturnData.setMessage("您选择的机构的当天预约名额已满，请选择其它体检机构或其它日期进行预约！");
            return ajaxReturnData;
        }

        ajaxReturnData.setResult(true);
        ajaxReturnData.setMessage("预约信息CHECK成功");
        return ajaxReturnData;
    }

    /**
     *  体检人员修改
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "health/toModifyUser")
    public ModelAndView toModifyUser(HttpServletRequest request, String userId) {
        ModelAndView view = new ModelAndView("operation/health/userEdit");
        // 登录者自己部门的检索条件
        MemberBase memberBase = (MemberBase)request.getSession().getAttribute("memInfo");
        if (memberBase != null && memberBase.getHealthDeptId() != null ) {
            view = new ModelAndView("operation/health/userEdit_new");
        }
        view.addObject("memberBase", memberBase);

        // 用户新增的取得，以及用户体检预约信息的取得
        HealthUser healthUser = healthUserMapper.selectByPrimaryKey(Integer.valueOf(userId));
        view.addObject("healthUser", healthUser);
        HealthUserAppointment healthUserAppointment = new HealthUserAppointment();
        healthUserAppointment.setUserId(Integer.valueOf(userId));
        healthUserAppointment.setPageSwitch(false);
        List<HealthUserAppointment> huaList = healthUserAppointmentMapper.selectListByCondition(healthUserAppointment);
        if (huaList != null && huaList.size() > 0) {
            healthUserAppointment = huaList.get(0);
        }
        view.addObject("healthUserAppointment", healthUserAppointment);

        // 可选择体检机构的取得
        AjaxReturnEntity orgAjaxReturnEntity = getOrgOption(String.valueOf(healthUser.getDeptId()), null, healthUser.getPkgType(), healthUser.getHaveDoneOptionalOption(), healthUserAppointment.getNeedOptionalOption());
        if (orgAjaxReturnEntity.isResult()) {
            view.addObject("orgList", orgAjaxReturnEntity.getList());
        }

        // 可选择业务单元的取得
        HealthDept healthDept = new HealthDept();
        healthDept.setPageSwitch(false);
        List<HealthDept> healthDeptList = healthDeptMapper.selectListByCondition(healthDept);
        view.addObject("deptList", healthDeptList);

        // 套餐类型的取得
        AjaxReturnEntity pkgTypeReturnEntity = getPkgTypeOption(healthUser.getUserSex(), String.valueOf(healthUser.getUserAge()));
        if (pkgTypeReturnEntity.isResult()) {
            view.addObject("pkgTypeList", pkgTypeReturnEntity.getList());
        }

        // 胸部CT的选择、必选项的选择、自选项的选择
        List<String> breastCTList = new ArrayList<String>();
        List<String> requiredOptionList = new ArrayList<String>();
        List<String> optionalOptionList = new ArrayList<String>();
        String orgName = healthUserAppointment.getOrgName();
        String pkgType = healthUserAppointment.getPkgType();
        String haveDoneOptionalOption = healthUser.getHaveDoneOptionalOption();
        String needOptionalOption = healthUserAppointment.getNeedOptionalOption();
        if (StringUtils.isNotBlank(orgName)) {
            if (pkgType.equals("B1") || pkgType.equals("B2")) {
                if ("是".equals(needOptionalOption)) {
                    if (orgName.equals("北京电力医院(含无痛胃肠镜)") || orgName.equals("北京航天中心医院(含无痛胃肠镜)")) {
                        // 设置必选项
                        requiredOptionList.add("①心脑血管风险筛查");
                        requiredOptionList.add("②关节痛检测");
                        requiredOptionList.add("③复检、待检卡");

                        // 设置自选项
                        optionalOptionList.add("无痛胃肠镜");
                    }

                    if (orgName.equals("福临门大厦上门体检")) {
                        // 设置自选项
                        optionalOptionList.add("无痛胃肠镜");
                    }
                }

                if ("否".equals(needOptionalOption)) {
                    if (orgName.equals("北京电力医院(不含无痛胃肠镜)") || orgName.equals("北京航天中心医院(不含无痛胃肠镜)")) {
                        // 设置必选项
                        requiredOptionList.add("①心脑血管风险筛查");
                        requiredOptionList.add("②关节痛检测");
                        requiredOptionList.add("③复检、待检卡");
                    }

                    if (orgName.equals("福临门大厦上门体检")) {
                        // 无必选项
                    }
                }
            }

            if (pkgType.equals("C1") || pkgType.equals("C2") || pkgType.equals("C3") || pkgType.equals("C4")) {
                if ("否".equals(haveDoneOptionalOption) && "是".equals(needOptionalOption)) {
                    if (orgName.equals("美兆东方广场分院") || orgName.equals("美兆润美分院")) {
                        // 设置自选项
                        optionalOptionList.add("无痛胃肠镜");
                    }

                    if (orgName.equals("北京电力医院(含无痛胃肠镜)")) {
                        // 设置必选项
                        requiredOptionList.add("①心脏冠状动脉CT");
                        requiredOptionList.add("②亚健康及慢性病风险检测");
                        requiredOptionList.add("③关节痛检测");
                        requiredOptionList.add("④头部血管核磁造影");

                        // 设置自选项
                        optionalOptionList.add("无痛胃肠镜");
                    }

                    if (orgName.equals("北京航天中心医院(含无痛胃肠镜)")) {
                        // 设置必选项
                        requiredOptionList.add("①心脏冠状动脉CT");
                        requiredOptionList.add("②关节痛检测");
                        requiredOptionList.add("③头部血管核磁造影");

                        // 设置自选项
                        optionalOptionList.add("无痛胃肠镜");
                    }

                    if (orgName.equals("福临门大厦上门体检")) {
                        // 设置自选项
                        optionalOptionList.add("无痛胃肠镜");
                    }
                }

                if ("是".equals(haveDoneOptionalOption) || ("否".equals(haveDoneOptionalOption) && "否".equals(needOptionalOption))) {
                    if (orgName.equals("美兆东方广场分院") || orgName.equals("美兆润美分院")) {
                        // 无必选项
                    }

                    if (orgName.equals("爱康双子座君安分院") || orgName.equals("爱康大望路分院") || orgName.equals("爱康光华路SOHO分院")) {
                        // 设置必选项
                        requiredOptionList.add("①头部核磁+胸部CT+颈椎X光");
                        requiredOptionList.add("②头部核磁+胸部CT+腰椎X光");
                        requiredOptionList.add("③胸部核磁+头部CT+颈椎X光");
                        requiredOptionList.add("④胸部核磁+头部CT+腰椎X光");
                        requiredOptionList.add("⑤无核磁");
                    }

                    if (orgName.equals("北京电力医院(不含无痛胃肠镜)")) {
                        // 设置必选项
                        requiredOptionList.add("①心脏冠状动脉CT");
                        requiredOptionList.add("②亚健康及慢性病风险检测");
                        requiredOptionList.add("③关节痛检测");
                        requiredOptionList.add("④头部血管核磁造影");
                    }

                    if (orgName.equals("北京航天中心医院(不含无痛胃肠镜)")) {
                        // 设置必选项
                        requiredOptionList.add("①心脏冠状动脉CT");
                        requiredOptionList.add("②关节痛检测");
                        requiredOptionList.add("③头部血管核磁造影");
                    }

                    if (orgName.equals("福临门大厦上门体检")) {
                        // 无必选项
                    }
                }
            }

            if (pkgType.equals("D1") || pkgType.equals("D2") || pkgType.equals("D3") || pkgType.equals("D4")) {
                if ("是".equals(needOptionalOption)) {
                    if (orgName.equals("北京电力医院D") || orgName.equals("北京航天中心医院(西三环)") || orgName.equals("福临门大厦上门体检") || orgName.equals("北京航天中心医院(玉泉路D)")) {
                        // 设置自选项
                        optionalOptionList.add("无痛胃肠镜");
                    }
                }

                if ("否".equals(needOptionalOption)) {
                    if (orgName.equals("美兆东方广场分院") || orgName.equals("美兆润美分院") || orgName.equals("爱康双子座君安分院") || orgName.equals("爱康大望路分院") || orgName.equals("爱康光华路SOHO分院")) {
                        breastCTList.add("有胸部CT");
                    }

                    if (orgName.equals("北京中医医院")) {
                        // 无任何选项
                    }

                    if (orgName.equals("北京电力医院D")) {
                        requiredOptionList.add("①心血管危险因素筛查");
                        requiredOptionList.add("②糖尿病风险筛查");
                    }

                    if (orgName.equals("北京航天中心医院(西三环)") || orgName.equals("福临门大厦上门体检") || orgName.equals("北京航天中心医院(玉泉路D)")) {
                        requiredOptionList.add("①心血管危险因素筛查");
                        requiredOptionList.add("②胃功能筛查");
                        requiredOptionList.add("③心脏彩超检查");
                    }
                }
            }
        }

//        view.addObject("psychologicalAssessmentCheckOptionList", Arrays.asList("是", "否"));

        if (StringUtils.equals(healthUser.getPkgType(), "B1") || StringUtils.equals(healthUser.getPkgType(), "B2")) {
            view.addObject("needOptionalOptionList", Arrays.asList("是", "否"));
            view.addObject("haveDoneOptionalOptionList", new ArrayList<String>());
        } else if (StringUtils.equals(healthUser.getPkgType(), "C1") || StringUtils.equals(healthUser.getPkgType(), "C2") || StringUtils.equals(healthUser.getPkgType(), "C3") || StringUtils.equals(healthUser.getPkgType(), "C4")) {
            view.addObject("haveDoneOptionalOptionList", Arrays.asList("是", "否"));
            if ("否".equals(haveDoneOptionalOption)) {
                view.addObject("needOptionalOptionList", Arrays.asList("是", "否"));
            } else {
                view.addObject("needOptionalOptionList", new ArrayList<String>());
            }
        } else if (StringUtils.equals(healthUser.getPkgType(), "D1") || StringUtils.equals(healthUser.getPkgType(), "D2") || StringUtils.equals(healthUser.getPkgType(), "D3") || StringUtils.equals(healthUser.getPkgType(), "D4")) {
            view.addObject("needOptionalOptionList", Arrays.asList("是", "否"));
            view.addObject("haveDoneOptionalOptionList", new ArrayList<String>());
        } else {
            view.addObject("haveDoneOptionalOptionList", new ArrayList<String>());
            view.addObject("needOptionalOptionList", new ArrayList<String>());
        }
        // haveDoneOptionalOptionList
        // dClassNeedOptionalOptionList

        view.addObject("breastCTList", breastCTList);
        view.addObject("requiredOptionList", requiredOptionList);
        view.addObject("optionalOptionList", optionalOptionList);

        return view;
    }
    @RequestMapping(value = "health/userDoEdit")
    public ModelAndView doEditUser(HttpServletRequest request, HealthUser healthUser, HealthUserAppointment vmHuaInfo) {
        ModelAndView modelAndView = new ModelAndView("msg");
        if ("是".equals(vmHuaInfo.getNeedOptionalOption())) {
            vmHuaInfo.setOptionalOption("无痛胃肠镜");
        }

        // 判断套餐类型是否会因为在体检日期当天用户的年龄达到了40岁而发生变化
        if ("2".equals(healthUser.getState()) && healthUser.getUserAge() == 39 && StringUtils.isNotBlank(vmHuaInfo.getCheckDateStr())) {
            if (healthUser.getPkgType().startsWith("C") || healthUser.getPkgType().startsWith("D")) {
                // 计算体检日期当天，用户的年龄
                Date checkDate = DateUtil.strToDate(vmHuaInfo.getCheckDateStr(), DateUtil.DEFAULT_DATE_PATTERN);
                int age = CalculateUserAgeUtils.calculate(healthUser.getCardId(), checkDate);
                if (age == 40) {
                    ModelAndView view = new ModelAndView("msg");
                    view.addObject("msg", "发现预约日期跨越40岁 提前预约日期会产生套餐变更 请联系管理员");
                    view.addObject("returnUrl", "operation/health/userList");
                    return view;
                }
            }
        }

        // 更新
        boolean updateResult = healthUserService.updateUserAndUserAppointment(healthUser, vmHuaInfo);
        if (updateResult) {
            modelAndView.addObject("msg", "体检人员修改成功");
        } else {
            modelAndView.addObject("msg", "体检人员修改失败");
        }
        modelAndView.addObject("returnUrl", "operation/health/userList");
        return modelAndView;
    }

    /**
     *  体检人员删除
     *
     * @param request
     * @return
     */
    @RequestMapping("health/delUser")
    public ModelAndView delUser(HttpServletRequest request) {
        String[] userId = request.getParameterValues("userId");
        int i = 0;
        for (String id : userId) {
            i += healthUserMapper.deleteByPrimaryKey(Integer.parseInt(id));
        }
        ModelAndView modelAndView = new ModelAndView("msg");
        if (i == userId.length) {
            modelAndView.addObject("msg", "体检人员删除成功");
        } else {
            modelAndView.addObject("msg", "体检人员删除失败");
        }
        modelAndView.addObject("returnUrl", "operation/health/userList");
        return modelAndView;
    }

    /**
     * 体检报告领取批量通知
     *
     * @param multipartRequeste
     * @return
     */
    @RequestMapping(value = "health/reportGetUpload")
    @ResponseBody
    public String reportGetUpload(MultipartHttpServletRequest multipartRequeste){

        try {

            Iterator<Map.Entry<String,MultipartFile>> it =  multipartRequeste.getFileMap().entrySet().iterator();

            if (!it.hasNext()) {
                return "没有选择批量通知对象数据文件";
            }

            // 文件上传
            MultipartFile multipartFile = it.next().getValue();
            String extName = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            String tempDir = System.getProperty("user.dir");
            String name = new Date().getTime() + extName.toLowerCase();
            String filName = tempDir.concat(File.separator).concat(name);
            File targetFile = new File(filName);

            try {
                multipartFile.transferTo(targetFile);
            } catch (IOException e) {
                e.printStackTrace();
                return "文件上传失败";
            }

            // 文件内容的读取
            Map<Integer, Map<Integer, String>> mapContent = null;
            try {
                mapContent = ExcelUtil.readExcelContent(targetFile);
            } catch (Exception e) {
                e.printStackTrace();
                return "文件读取失败";
            }

            if (mapContent.size() <= 1) {
                return "文件内没有数据";
            }

            // 文件数据的设定
            // 错误信息列表
            List<String> errorList = new ArrayList<String>();
            String errMsg = null;
            // 体检报告领取批量通知对象数据
            List<HealthUser> healthUserList = new ArrayList<HealthUser>();
            HealthUser healthUser = null;
            // 列编号
            int colIndex = 0;
            String strCell = null;
            // 第一行为标题
            for (int i = 1; i < mapContent.size(); i++) {
                Map<Integer, String> rowContent = mapContent.get(i);

                // 业务单元信息的设定
                healthUser = new HealthUser();
                errMsg = "";

                // 序号
                colIndex = 0;
                strCell = rowContent.get(colIndex);
                if (strCell == null || "".equals(strCell.trim())) {
                    break;
                }

                // 手机号
                colIndex = colIndex + 1;
                strCell = rowContent.get(colIndex);
                if (StringUtils.isBlank(strCell)) {
                    errMsg = errMsg.concat("手机号不能为空。");
                } else {
                    healthUser.setMobPhone(strCell.trim());
                }

                // 重复check判断用
                healthUserList.add(healthUser);

                // 错误信息有无的判断
                if (!"".equals(errMsg.trim())) {
                    errMsg = errMsg.substring(0, errMsg.length()-1);
                    errMsg = "第" + i + "条数据的错误信息：" + errMsg;
                    errorList.add(errMsg);
                    continue;
                }
            }

            // 临时文件的删除
            final String fullname = filName;
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    new File(fullname).delete();
                }
            }, 10000);

            // 数据文件内重复数据的判断
            HealthUser healthUser1 = null;
            HealthUser healthUser2 = null;
            for (int i = 0; i<healthUserList.size(); i++) {
                healthUser1 = healthUserList.get(i);
                for (int j = i+1; j<healthUserList.size(); j++) {
                    healthUser2 = healthUserList.get(j);
                    errMsg = "";

                    if (StringUtils.isNotEmpty(healthUser1.getMobPhone()) && StringUtils.isNotEmpty(healthUser2.getMobPhone())) {
                        if (healthUser1.getMobPhone().equals(healthUser2.getMobPhone())) {
                            errMsg = errMsg + "手机号相同。";
                        }
                    }

                    if (!"".equals(errMsg.trim())) {
                        errMsg = errMsg.substring(0, errMsg.length()-1);
                        errMsg = "第" + (i+1) + "条数据和第" + (j+1) + "条数据的" + errMsg;
                        errorList.add(errMsg);
                    }
                }
            }

            // 有错误信息时
            if (errorList.size() > 0) {
                String jsonStr = "ERROR_LIST:" + JSON.toJSONString(errorList);
                return jsonStr;
            }

            // 批量通知
            AjaxReturnData ajaxReturnData = healthUserService.reportGetList(healthUserList);

            // ajaxReturnData.Result = false --->> 数据库内有业务单元名称相同的数据
            // ajaxReturnData.Result = true --->> 导入成功
            return ajaxReturnData.getMessage();
        }  catch (Exception e) {
            e.printStackTrace();
            logger.error("异常信息:", e.getMessage());
            logger.error(e.getLocalizedMessage());
            return "数据导入失败，请联系相关人员确认";
        }
    }

    /**
     * 单个通知体检报告领取
     *
     * @param request
     * @return
     */
    @RequestMapping("health/healthReportGet")
    @ArchivesLog(operationDescription = "单个通知体检报告领取")
    public ModelAndView toModifySign(HttpServletRequest request, Integer userId) {

        ModelAndView modelAndView = new ModelAndView("msg");

        AjaxReturnData ajaxReturnData = healthUserService.reportGet(userId);

        if (ajaxReturnData.isResult()) {
            modelAndView.addObject("msg", "通知成功");
        } else {
            modelAndView.addObject("msg", "通知失败");
        }

        modelAndView.addObject("returnUrl", "operation/health/userList");
        return modelAndView;
    }

    /**
     *  取消体检车的体检日期
     * @param cancelCarDate
     * @return
     */
    @Transactional
    @RequestMapping("health/cancelCarDate")
    @ResponseBody
    public AjaxReturnData cancelCarDate(String cancelCarDate) {
        AjaxReturnData result = new AjaxReturnData();

        int appointmentDate = DateUtil.toUnixTimeStampByDate(cancelCarDate);

        // STEP.1 获取体检机构id
        HealthOrg healthOrg = new HealthOrg();
        healthOrg.setPageSwitch(false);
        healthOrg.setOrgName("福临门大厦上门体检");
        List<HealthOrg> healthOrgList = healthOrgMapper.selectListByCondition(healthOrg);
        if (healthOrgList.size() != 1 || healthOrgList.get(0) == null) {
            result.setResult(false);
            result.setMessage("体检机构数据异常");
            return result;
        }
        final Integer orgId = healthOrgList.get(0).getOrgId();

        // STEP.2 将体检机构的预约人数设置为0
        healthOrgAppointmentMapper.updateAppointmenterNumByOrgIdAndAppointmentDate(orgId, appointmentDate, 0);

        // STEP.3 获取已经预约的人员id
        HealthUserAppointment huaSearch = new HealthUserAppointment();
        huaSearch.setPageSwitch(false);
        huaSearch.setOrgId(orgId);
        huaSearch.setCheckDate(appointmentDate);
        List<HealthUserAppointment> healthUserAppointments = healthUserAppointmentMapper.selectListByCondition(huaSearch);
        Set<Integer> userIdSet = new HashSet<Integer>();
        for (HealthUserAppointment healthUserAppointment : healthUserAppointments) {
            if (healthUserAppointment.getCancelTime() == null) {
                userIdSet.add(healthUserAppointment.getUserId());
            }
        }

        // STEP.4 修改已经预约人员的状态为"已取消"、并取消原来的预约,
        for (Integer userId : userIdSet) {
            HealthUser healthUser = new HealthUser();
            healthUser.setUserId(userId);
            healthUser.setState("3");
            healthUserMapper.updateByPrimaryKeySelective(healthUser);

            healthUserAppointmentMapper.cancelAppointment(orgId, userId, DateUtil.unixTimeStampInt().intValue());
        }

        // STEP.5 发送短信提醒
        for (Integer userId : userIdSet) {
            String mobPhone = healthUserMapper.selectByPrimaryKey(userId).getMobPhone();
            try {
                //取消成功短信模板取得
                MemberMsgTpl memberMsgTpl = memberMsgTplMapper.selectByPrimaryKey("health_car_cancel_msg");
                Map<String, Object> smsMap = new HashMap<String, Object>();
                smsMap.put("moblieNumber", mobPhone);
                // 【中粮集团医疗保障室】因航天医院体检车未能如期到达福临门大厦，您{1}的体检预约，系统已经取消。请你您再次重新预约，对此表示深切的歉意，请您及时预约其他日期。
                String[] params = new String[1];
                params[0] = cancelCarDate;
                smsMap.put("params", params);
                messageAndNoticeService.sendMessageAndNotice(memberMsgTpl, smsMap, null, null, null);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("手机号【" + mobPhone + "】的短信发送失败：", e);
            } finally {
                System.out.println("手机号【" + mobPhone + "】的短信发送结束。。。。。");
            }
        }

        result.setResult(true);
        return result;
    }

    /**
     *  调整体检车的体检日期
     * @param oldCarDate
     * @param newCarDate
     * @return
     */
    @Transactional
    @RequestMapping("health/adjustCarDate")
    @ResponseBody
    public AjaxReturnData adjustCarDate(@RequestParam("oldCarDate") String oldCarDate, @RequestParam("newCarDate") String newCarDate) {
        AjaxReturnData result = new AjaxReturnData();

        int oldAppointmentDate = DateUtil.toUnixTimeStampByDate(oldCarDate);
        int newAppointmentDate = DateUtil.toUnixTimeStampByDate(newCarDate);

        // STEP.1 获取体检机构id
        HealthOrg healthOrg = new HealthOrg();
        healthOrg.setPageSwitch(false);
        healthOrg.setOrgName("福临门大厦上门体检");
        List<HealthOrg> healthOrgList = healthOrgMapper.selectListByCondition(healthOrg);
        if (healthOrgList.size() != 1 || healthOrgList.get(0) == null) {
            result.setResult(false);
            result.setMessage("体检机构数据异常");
            return result;
        }
        final Integer orgId = healthOrgList.get(0).getOrgId();

        // STEP.2 将体检机构的预约人数设置为0
        healthOrgAppointmentMapper.updateAppointmenterNumByOrgIdAndAppointmentDate(orgId, oldAppointmentDate, 0);

        // STEP.3 获取已经预约的人员id
        HealthUserAppointment huaSearch = new HealthUserAppointment();
        huaSearch.setPageSwitch(false);
        huaSearch.setOrgId(orgId);
        huaSearch.setCheckDate(oldAppointmentDate);
        List<HealthUserAppointment> healthUserAppointments = healthUserAppointmentMapper.selectListByCondition(huaSearch);
        Set<Integer> userIdSet = new HashSet<Integer>();
        Set<Integer> uaIdSet = new HashSet<Integer>();
        for (HealthUserAppointment healthUserAppointment : healthUserAppointments) {
            if (healthUserAppointment.getCancelTime() == null) {
                userIdSet.add(healthUserAppointment.getUserId());
                uaIdSet.add(healthUserAppointment.getUaId());
            }
        }

        // STEP.4 修改取消原来的预约, 并新增新的预约
        int appointmentDate = DateUtil.unixTimeStampInt().intValue();
        for (Integer uaId : uaIdSet) {
            // 增加新预约
            healthUserAppointmentMapper.copyAppointment(uaId, newAppointmentDate, appointmentDate);

            // 取消旧预约
            healthUserAppointmentMapper.cancelAppointmentByUaId(uaId, appointmentDate);
        }

        // STEP.5 校验预约名额是否超出限制
        HealthOrgAppointment orgAppointment = new HealthOrgAppointment();
        orgAppointment.setOrgId(orgId);
        orgAppointment.setAppointmentDate(newAppointmentDate);
        List<HealthOrgAppointment> orgAppointmentList = healthOrgAppointmentMapper.selectListByCondition(orgAppointment);
        if (orgAppointmentList == null || orgAppointmentList.size() == 0 || orgAppointmentList.size() > 1) {
            throw new RuntimeException("您预约的体检机构的数据不正确，请联系管理员.");
        }
        // 只取一条
        orgAppointment = orgAppointmentList.get(0);

        // 该结构已经预约了的人数的取得
        HealthUserAppointment userAppointment = new HealthUserAppointment();
        userAppointment.setOrgId(orgId);
        userAppointment.setCheckDate(newAppointmentDate);
        userAppointment.setAppointmentedFlg("1");       // 已预约的
        userAppointment.setPageSwitch(false);
        List<HealthUserAppointment> userAppointmentList = healthUserAppointmentMapper.selectListByCondition(userAppointment);

        if (orgAppointment.getAppointmenterNum() <= userAppointmentList.size()) {
            throw new RuntimeException("您选择的机构的当天预约名额已满，请选择其它体检机构或其它日期进行预约！");
        }

        // STEP.6 发送短信提醒
        for (Integer userId : userIdSet) {
            String mobPhone = healthUserMapper.selectByPrimaryKey(userId).getMobPhone();
            try {
                //取消成功短信模板取得
                MemberMsgTpl memberMsgTpl = memberMsgTplMapper.selectByPrimaryKey("health_car_adjust_msg");
                Map<String, Object> smsMap = new HashMap<String, Object>();
                smsMap.put("moblieNumber", mobPhone);
                // 【中粮集团医疗保障室】因体检场地占用原因，您预约的体检日期:{1}的上门体检无法进行，您的体检日期变更至{2}新日期。带来不便，敬请谅解！
                String[] params = new String[2];
                params[0] = oldCarDate;
                params[1] = newCarDate;
                smsMap.put("params", params);
                messageAndNoticeService.sendMessageAndNotice(memberMsgTpl, smsMap, null, null, null);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("手机号【" + mobPhone + "】的短信发送失败：", e);
            } finally {
                System.out.println("手机号【" + mobPhone + "】的短信发送结束。。。。。");
            }
        }

        result.setResult(true);
        return result;
    }
}
